blob: 503a27ef3f913023e43343fb8495642942cc2652 [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.
94 if (LastWarningLoc == Loc)
95 return;
96 LastWarningLoc = Loc;
97
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
540public:
Chandler Carruth84f36192011-09-25 22:54:56 +0000541 TextDiagnostic(TextDiagnosticPrinter &Printer,
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000542 raw_ostream &OS,
543 const SourceManager &SM,
544 const LangOptions &LangOpts,
Chandler Carruth3236f0d2011-09-25 22:31:58 +0000545 const DiagnosticOptions &DiagOpts)
546 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts) {
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000547 }
548
Chandler Carruthc38c7b12011-10-15 11:09:19 +0000549 void Emit(SourceLocation Loc, DiagnosticsEngine::Level Level,
550 StringRef Message, ArrayRef<CharSourceRange> Ranges,
551 ArrayRef<FixItHint> FixItHints,
552 FullSourceLoc LastLoc = FullSourceLoc(),
553 bool LastCaretDiagnosticWasNote = false) {
554 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
555
556 // First, if this diagnostic is not in the main file, print out the
557 // "included from" lines.
558 Printer.PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
559
560 uint64_t StartOfLocationInfo = OS.tell();
561
562 // Next emit the location of this particular diagnostic.
563 Printer.EmitDiagnosticLoc(Loc, PLoc, Level, Ranges, SM);
564
565 if (DiagOpts.ShowColors)
566 OS.resetColor();
567
568 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
569 printDiagnosticMessage(OS, Level, Message,
570 OS.tell() - StartOfLocationInfo,
571 DiagOpts.MessageLength, DiagOpts.ShowColors);
572
573 // If caret diagnostics are enabled and we have location, we want to
574 // emit the caret. However, we only do this if the location moved
575 // from the last diagnostic, if the last diagnostic was a note that
576 // was part of a different warning or error diagnostic, or if the
577 // diagnostic has ranges. We don't want to emit the same caret
578 // multiple times if one loc has multiple diagnostics.
579 if (DiagOpts.ShowCarets &&
580 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
581 (LastCaretDiagnosticWasNote && Level != DiagnosticsEngine::Note))) {
582 // Get the ranges into a local array we can hack on.
583 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
584 Ranges.end());
585
586 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
587 E = FixItHints.end();
588 I != E; ++I)
589 if (I->RemoveRange.isValid())
590 MutableRanges.push_back(I->RemoveRange);
591
592 unsigned MacroDepth = 0;
593 EmitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
594 }
595 }
596
Chandler Carruth09c74642011-10-15 01:21:55 +0000597 /// \brief Emit the caret and underlining text.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000598 ///
599 /// Walks up the macro expansion stack printing the code snippet, caret,
600 /// underlines and FixItHint display as appropriate at each level. Walk is
601 /// accomplished by calling itself recursively.
602 ///
Chandler Carruth09c74642011-10-15 01:21:55 +0000603 /// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
604 /// caret diagnostics.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000605 /// FIXME: Break up massive function into logical units.
606 ///
607 /// \param Loc The location for this caret.
608 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000609 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000610 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000611 /// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth09c74642011-10-15 01:21:55 +0000612 void EmitCaret(SourceLocation Loc,
Chandler Carruth773757a2011-09-07 01:47:09 +0000613 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000614 ArrayRef<FixItHint> Hints,
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000615 unsigned &MacroDepth,
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000616 unsigned OnMacroInst = 0) {
617 assert(!Loc.isInvalid() && "must have a valid source location here");
618
Chandler Carruth9d229f32011-09-25 06:59:38 +0000619 // If this is a file source location, directly emit the source snippet and
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000620 // caret line. Also record the macro depth reached.
621 if (Loc.isFileID()) {
622 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
623 MacroDepth = OnMacroInst;
624 EmitSnippetAndCaret(Loc, Ranges, Hints);
625 return;
626 }
Chandler Carruth9d229f32011-09-25 06:59:38 +0000627 // Otherwise recurse through each macro expansion layer.
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000628
Chandler Carruth9d229f32011-09-25 06:59:38 +0000629 // When processing macros, skip over the expansions leading up to
630 // a macro argument, and trace the argument's expansion stack instead.
631 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000632
Chandler Carruth9d229f32011-09-25 06:59:38 +0000633 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000634
Chandler Carruth9d229f32011-09-25 06:59:38 +0000635 // FIXME: Map ranges?
Chandler Carruth09c74642011-10-15 01:21:55 +0000636 EmitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000637
Chandler Carruth9d229f32011-09-25 06:59:38 +0000638 // Map the location.
639 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000640
Chandler Carruthcb8f82a2011-09-25 22:27:52 +0000641 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
642 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
643 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
644 DiagOpts.MacroBacktraceLimit % 2;
645 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
646 }
647
648 // Whether to suppress printing this macro expansion.
649 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
650 OnMacroInst < MacroSkipEnd);
651
Chandler Carruth9d229f32011-09-25 06:59:38 +0000652 // Map the ranges.
653 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
654 E = Ranges.end();
655 I != E; ++I) {
656 SourceLocation Start = I->getBegin(), End = I->getEnd();
657 if (Start.isMacroID())
658 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
659 if (End.isMacroID())
660 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
661 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000662
Chandler Carruth9d229f32011-09-25 06:59:38 +0000663 if (!Suppressed) {
664 // Don't print recursive expansion notes from an expansion note.
665 Loc = SM.getSpellingLoc(Loc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000666
Chandler Carruth9d229f32011-09-25 06:59:38 +0000667 // Get the pretty name, according to #line directives etc.
668 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
669 if (PLoc.isInvalid())
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000670 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000671
Chandler Carruth9d229f32011-09-25 06:59:38 +0000672 // If this diagnostic is not in the main file, print out the
673 // "included from" lines.
David Blaikie9c902b52011-09-25 23:23:43 +0000674 Printer.PrintIncludeStack(DiagnosticsEngine::Note, PLoc.getIncludeLoc(),
675 SM);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000676
Chandler Carruth9d229f32011-09-25 06:59:38 +0000677 if (DiagOpts.ShowLocation) {
678 // Emit the file/line/column that this expansion came from.
679 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
680 if (DiagOpts.ShowColumn)
681 OS << PLoc.getColumn() << ':';
682 OS << ' ';
683 }
684 OS << "note: expanded from:\n";
685
686 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000687 return;
688 }
689
Chandler Carruth9d229f32011-09-25 06:59:38 +0000690 if (OnMacroInst == MacroSkipStart) {
691 // Tell the user that we've skipped contexts.
692 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
693 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
694 "all)\n";
695 }
696 }
697
698 /// \brief Emit a code snippet and caret line.
699 ///
700 /// This routine emits a single line's code snippet and caret line..
701 ///
702 /// \param Loc The location for the caret.
703 /// \param Ranges The underlined ranges for this code snippet.
704 /// \param Hints The FixIt hints active for this diagnostic.
705 void EmitSnippetAndCaret(SourceLocation Loc,
706 SmallVectorImpl<CharSourceRange>& Ranges,
707 ArrayRef<FixItHint> Hints) {
708 assert(!Loc.isInvalid() && "must have a valid source location here");
709 assert(Loc.isFileID() && "must have a file location here");
710
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000711 // Decompose the location into a FID/Offset pair.
712 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
713 FileID FID = LocInfo.first;
714 unsigned FileOffset = LocInfo.second;
715
716 // Get information about the buffer it points into.
717 bool Invalid = false;
718 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
719 if (Invalid)
720 return;
721
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000722 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000723 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
724 unsigned CaretEndColNo
725 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
726
727 // Rewind from the current position to the start of the line.
728 const char *TokPtr = BufStart+FileOffset;
729 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
730
731
732 // Compute the line end. Scan forward from the error position to the end of
733 // the line.
734 const char *LineEnd = TokPtr;
735 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
736 ++LineEnd;
737
738 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
739 // the source line length as currently being computed. See
740 // test/Misc/message-length.c.
741 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
742
743 // Copy the line of code into an std::string for ease of manipulation.
744 std::string SourceLine(LineStart, LineEnd);
745
746 // Create a line for the caret that is filled with spaces that is the same
747 // length as the line of source code.
748 std::string CaretLine(LineEnd-LineStart, ' ');
749
750 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000751 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
752 E = Ranges.end();
753 I != E; ++I)
Chandler Carruth97798302011-09-07 07:02:31 +0000754 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000755
756 // Next, insert the caret itself.
757 if (ColNo-1 < CaretLine.size())
758 CaretLine[ColNo-1] = '^';
759 else
760 CaretLine.push_back('^');
761
Chandler Carruthe79ddf82011-09-07 05:36:50 +0000762 ExpandTabs(SourceLine, CaretLine);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000763
764 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
765 // to produce easily machine parsable output. Add a space before the
766 // source line and the caret to make it trivial to tell the main diagnostic
767 // line from what the user is intended to see.
768 if (DiagOpts.ShowSourceRanges) {
769 SourceLine = ' ' + SourceLine;
770 CaretLine = ' ' + CaretLine;
771 }
772
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000773 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000774 LineStart, LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000775 Hints);
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000776
777 // If the source line is too long for our terminal, select only the
778 // "interesting" source region within that line.
Chandler Carruth3236f0d2011-09-25 22:31:58 +0000779 unsigned Columns = DiagOpts.MessageLength;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000780 if (Columns && SourceLine.size() > Columns)
781 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
782 CaretEndColNo, Columns);
783
784 // Finally, remove any blank spaces from the end of CaretLine.
785 while (CaretLine[CaretLine.size()-1] == ' ')
786 CaretLine.erase(CaretLine.end()-1);
787
788 // Emit what we have computed.
789 OS << SourceLine << '\n';
790
791 if (DiagOpts.ShowColors)
792 OS.changeColor(caretColor, true);
793 OS << CaretLine << '\n';
794 if (DiagOpts.ShowColors)
795 OS.resetColor();
796
797 if (!FixItInsertionLine.empty()) {
798 if (DiagOpts.ShowColors)
799 // Print fixit line in color
800 OS.changeColor(fixitColor, false);
801 if (DiagOpts.ShowSourceRanges)
802 OS << ' ';
803 OS << FixItInsertionLine << '\n';
804 if (DiagOpts.ShowColors)
805 OS.resetColor();
806 }
807
Chandler Carruthd3e83672011-09-02 06:30:30 +0000808 // Print out any parseable fixit information requested by the options.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000809 EmitParseableFixits(Hints);
Chandler Carruthd3e83672011-09-02 06:30:30 +0000810 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000811
Chandler Carruthd3e83672011-09-02 06:30:30 +0000812private:
Chandler Carruth97798302011-09-07 07:02:31 +0000813 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
814 void HighlightRange(const CharSourceRange &R,
815 unsigned LineNo, FileID FID,
816 const std::string &SourceLine,
817 std::string &CaretLine) {
818 assert(CaretLine.size() == SourceLine.size() &&
819 "Expect a correspondence between source and caret line!");
820 if (!R.isValid()) return;
821
822 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
823 SourceLocation End = SM.getExpansionLoc(R.getEnd());
824
825 // If the End location and the start location are the same and are a macro
826 // location, then the range was something that came from a macro expansion
827 // or _Pragma. If this is an object-like macro, the best we can do is to
828 // highlight the range. If this is a function-like macro, we'd also like to
829 // highlight the arguments.
830 if (Begin == End && R.getEnd().isMacroID())
831 End = SM.getExpansionRange(R.getEnd()).second;
832
833 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
834 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
835 return; // No intersection.
836
837 unsigned EndLineNo = SM.getExpansionLineNumber(End);
838 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
839 return; // No intersection.
840
841 // Compute the column number of the start.
842 unsigned StartColNo = 0;
843 if (StartLineNo == LineNo) {
844 StartColNo = SM.getExpansionColumnNumber(Begin);
845 if (StartColNo) --StartColNo; // Zero base the col #.
846 }
847
848 // Compute the column number of the end.
849 unsigned EndColNo = CaretLine.size();
850 if (EndLineNo == LineNo) {
851 EndColNo = SM.getExpansionColumnNumber(End);
852 if (EndColNo) {
853 --EndColNo; // Zero base the col #.
854
855 // Add in the length of the token, so that we cover multi-char tokens if
856 // this is a token range.
857 if (R.isTokenRange())
858 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
859 } else {
860 EndColNo = CaretLine.size();
861 }
862 }
863
864 assert(StartColNo <= EndColNo && "Invalid range!");
865
866 // Check that a token range does not highlight only whitespace.
867 if (R.isTokenRange()) {
868 // Pick the first non-whitespace column.
869 while (StartColNo < SourceLine.size() &&
870 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
871 ++StartColNo;
872
873 // Pick the last non-whitespace column.
874 if (EndColNo > SourceLine.size())
875 EndColNo = SourceLine.size();
876 while (EndColNo-1 &&
877 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
878 --EndColNo;
879
880 // If the start/end passed each other, then we are trying to highlight a
881 // range that just exists in whitespace, which must be some sort of other
882 // bug.
883 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
884 }
885
886 // Fill the range with ~'s.
887 for (unsigned i = StartColNo; i < EndColNo; ++i)
888 CaretLine[i] = '~';
889 }
890
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000891 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000892 const char *LineStart,
893 const char *LineEnd,
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000894 ArrayRef<FixItHint> Hints) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000895 std::string FixItInsertionLine;
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000896 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000897 return FixItInsertionLine;
898
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000899 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
900 I != E; ++I) {
901 if (!I->CodeToInsert.empty()) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000902 // We have an insertion hint. Determine whether the inserted
903 // code is on the same line as the caret.
904 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000905 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0f1006a2011-09-07 05:01:10 +0000906 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000907 // Insert the new code into the line just below the code
908 // that the user wrote.
909 unsigned HintColNo
910 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
911 unsigned LastColumnModified
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000912 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000913 if (LastColumnModified > FixItInsertionLine.size())
914 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000915 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth20bfaa0f2011-09-06 22:01:04 +0000916 FixItInsertionLine.begin() + HintColNo - 1);
917 } else {
918 FixItInsertionLine.clear();
919 break;
920 }
921 }
922 }
923
924 if (FixItInsertionLine.empty())
925 return FixItInsertionLine;
926
927 // Now that we have the entire fixit line, expand the tabs in it.
928 // Since we don't want to insert spaces in the middle of a word,
929 // find each word and the column it should line up with and insert
930 // spaces until they match.
931 unsigned FixItPos = 0;
932 unsigned LinePos = 0;
933 unsigned TabExpandedCol = 0;
934 unsigned LineLength = LineEnd - LineStart;
935
936 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
937 // Find the next word in the FixIt line.
938 while (FixItPos < FixItInsertionLine.size() &&
939 FixItInsertionLine[FixItPos] == ' ')
940 ++FixItPos;
941 unsigned CharDistance = FixItPos - TabExpandedCol;
942
943 // Walk forward in the source line, keeping track of
944 // the tab-expanded column.
945 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
946 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
947 ++TabExpandedCol;
948 else
949 TabExpandedCol =
950 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
951
952 // Adjust the fixit line to match this column.
953 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
954 FixItPos = TabExpandedCol;
955
956 // Walk to the end of the word.
957 while (FixItPos < FixItInsertionLine.size() &&
958 FixItInsertionLine[FixItPos] != ' ')
959 ++FixItPos;
960 }
961
962 return FixItInsertionLine;
963 }
964
Chandler Carruthe79ddf82011-09-07 05:36:50 +0000965 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
966 // Scan the source line, looking for tabs. If we find any, manually expand
967 // them to spaces and update the CaretLine to match.
968 for (unsigned i = 0; i != SourceLine.size(); ++i) {
969 if (SourceLine[i] != '\t') continue;
970
971 // Replace this tab with at least one space.
972 SourceLine[i] = ' ';
973
974 // Compute the number of spaces we need to insert.
975 unsigned TabStop = DiagOpts.TabStop;
976 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
977 "Invalid -ftabstop value");
978 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
979 assert(NumSpaces < TabStop && "Invalid computation of space amt");
980
981 // Insert spaces into the SourceLine.
982 SourceLine.insert(i+1, NumSpaces, ' ');
983
984 // Insert spaces or ~'s into CaretLine.
985 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
986 }
987 }
988
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000989 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthd3e83672011-09-02 06:30:30 +0000990 if (!DiagOpts.ShowParseableFixits)
991 return;
Chandler Carrutheef47ba2011-08-31 23:59:23 +0000992
Chandler Carruthd3e83672011-09-02 06:30:30 +0000993 // We follow FixItRewriter's example in not (yet) handling
994 // fix-its in macros.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +0000995 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
996 I != E; ++I) {
997 if (I->RemoveRange.isInvalid() ||
998 I->RemoveRange.getBegin().isMacroID() ||
999 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthd3e83672011-09-02 06:30:30 +00001000 return;
1001 }
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001002
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001003 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1004 I != E; ++I) {
1005 SourceLocation BLoc = I->RemoveRange.getBegin();
1006 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001007
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001008 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1009 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001010
Chandler Carruthd3e83672011-09-02 06:30:30 +00001011 // Adjust for token ranges.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001012 if (I->RemoveRange.isTokenRange())
1013 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001014
Chandler Carruthd3e83672011-09-02 06:30:30 +00001015 // We specifically do not do word-wrapping or tab-expansion here,
1016 // because this is supposed to be easy to parse.
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001017 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001018 if (PLoc.isInvalid())
1019 break;
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001020
Chandler Carruthd3e83672011-09-02 06:30:30 +00001021 OS << "fix-it:\"";
Chandler Carruth935574d2011-09-06 22:34:33 +00001022 OS.write_escaped(PLoc.getFilename());
Chandler Carruthd3e83672011-09-02 06:30:30 +00001023 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1024 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1025 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1026 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1027 << "}:\"";
Chandler Carruth1f28e6c2011-09-06 22:31:44 +00001028 OS.write_escaped(I->CodeToInsert);
Chandler Carruthd3e83672011-09-02 06:30:30 +00001029 OS << "\"\n";
Chandler Carrutheef47ba2011-08-31 23:59:23 +00001030 }
1031 }
1032};
1033
1034} // end namespace
1035
Chandler Carruth3d45b232011-09-07 08:05:58 +00001036/// \brief Print out the file/line/column information and include trace.
1037///
1038/// This method handlen the emission of the diagnostic location information.
1039/// This includes extracting as much location information as is present for the
1040/// diagnostic and printing it, as well as any include stack or source ranges
1041/// necessary.
Chandler Carruth342327ca2011-10-15 10:48:19 +00001042void TextDiagnosticPrinter::EmitDiagnosticLoc(SourceLocation Loc,
1043 PresumedLoc PLoc,
1044 DiagnosticsEngine::Level Level,
1045 ArrayRef<CharSourceRange> Ranges,
1046 const SourceManager &SM) {
Chandler Carruth3d45b232011-09-07 08:05:58 +00001047 if (PLoc.isInvalid()) {
1048 // At least print the file name if available:
Chandler Carruth342327ca2011-10-15 10:48:19 +00001049 FileID FID = SM.getFileID(Loc);
Chandler Carruth3d45b232011-09-07 08:05:58 +00001050 if (!FID.isInvalid()) {
1051 const FileEntry* FE = SM.getFileEntryForID(FID);
1052 if (FE && FE->getName()) {
1053 OS << FE->getName();
1054 if (FE->getDevice() == 0 && FE->getInode() == 0
1055 && FE->getFileMode() == 0) {
1056 // in PCH is a guess, but a good one:
1057 OS << " (in PCH)";
1058 }
1059 OS << ": ";
1060 }
1061 }
1062 return;
1063 }
1064 unsigned LineNo = PLoc.getLine();
1065
1066 if (!DiagOpts->ShowLocation)
1067 return;
1068
1069 if (DiagOpts->ShowColors)
1070 OS.changeColor(savedColor, true);
1071
1072 OS << PLoc.getFilename();
1073 switch (DiagOpts->Format) {
1074 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
1075 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
1076 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
1077 }
1078
1079 if (DiagOpts->ShowColumn)
1080 // Compute the column number.
1081 if (unsigned ColNo = PLoc.getColumn()) {
1082 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
1083 OS << ',';
1084 ColNo--;
1085 } else
1086 OS << ':';
1087 OS << ColNo;
1088 }
1089 switch (DiagOpts->Format) {
1090 case DiagnosticOptions::Clang:
1091 case DiagnosticOptions::Vi: OS << ':'; break;
1092 case DiagnosticOptions::Msvc: OS << ") : "; break;
1093 }
1094
Chandler Carruth342327ca2011-10-15 10:48:19 +00001095 if (DiagOpts->ShowSourceRanges && !Ranges.empty()) {
Chandler Carruth3d45b232011-09-07 08:05:58 +00001096 FileID CaretFileID =
Chandler Carruth342327ca2011-10-15 10:48:19 +00001097 SM.getFileID(SM.getExpansionLoc(Loc));
Chandler Carruth3d45b232011-09-07 08:05:58 +00001098 bool PrintedRange = false;
1099
Chandler Carruth342327ca2011-10-15 10:48:19 +00001100 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
1101 RE = Ranges.end();
1102 RI != RE; ++RI) {
Chandler Carruth3d45b232011-09-07 08:05:58 +00001103 // Ignore invalid ranges.
Chandler Carruth342327ca2011-10-15 10:48:19 +00001104 if (!RI->isValid()) continue;
Chandler Carruth3d45b232011-09-07 08:05:58 +00001105
Chandler Carruth342327ca2011-10-15 10:48:19 +00001106 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
1107 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
Chandler Carruth3d45b232011-09-07 08:05:58 +00001108
1109 // If the End location and the start location are the same and are a
1110 // macro location, then the range was something that came from a
1111 // macro expansion or _Pragma. If this is an object-like macro, the
1112 // best we can do is to highlight the range. If this is a
1113 // function-like macro, we'd also like to highlight the arguments.
Chandler Carruth342327ca2011-10-15 10:48:19 +00001114 if (B == E && RI->getEnd().isMacroID())
1115 E = SM.getExpansionRange(RI->getEnd()).second;
Chandler Carruth3d45b232011-09-07 08:05:58 +00001116
1117 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1118 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1119
1120 // If the start or end of the range is in another file, just discard
1121 // it.
1122 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1123 continue;
1124
1125 // Add in the length of the token, so that we cover multi-char
1126 // tokens.
1127 unsigned TokSize = 0;
Chandler Carruth342327ca2011-10-15 10:48:19 +00001128 if (RI->isTokenRange())
Chandler Carruth3d45b232011-09-07 08:05:58 +00001129 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1130
1131 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1132 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1133 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1134 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1135 << '}';
1136 PrintedRange = true;
1137 }
1138
1139 if (PrintedRange)
1140 OS << ':';
1141 }
1142 OS << ' ';
1143}
1144
Chandler Carruthcf259a42011-09-26 01:30:09 +00001145/// \brief Print the diagnostic name to a raw_ostream.
1146///
1147/// This prints the diagnostic name to a raw_ostream if it has one. It formats
1148/// the name according to the expected diagnostic message formatting:
1149/// " [diagnostic_name_here]"
1150static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruthb59f9cb92011-09-26 00:37:30 +00001151 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
1152 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
1153}
1154
Chandler Carruthcf259a42011-09-26 01:30:09 +00001155/// \brief Print any diagnostic option information to a raw_ostream.
1156///
1157/// This implements all of the logic for adding diagnostic options to a message
1158/// (via OS). Each relevant option is comma separated and all are enclosed in
1159/// the standard bracketing: " [...]".
1160static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth60740842011-09-26 00:44:09 +00001161 DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001162 const Diagnostic &Info,
Chandler Carruth60740842011-09-26 00:44:09 +00001163 const DiagnosticOptions &DiagOpts) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001164 bool Started = false;
Chandler Carruth60740842011-09-26 00:44:09 +00001165 if (DiagOpts.ShowOptionNames) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001166 // Handle special cases for non-warnings early.
1167 if (Info.getID() == diag::fatal_too_many_errors) {
1168 OS << " [-ferror-limit=]";
1169 return;
1170 }
1171
Daniel Dunbaraa111382011-09-29 01:01:08 +00001172 // The code below is somewhat fragile because we are essentially trying to
1173 // report to the user what happened by inferring what the diagnostic engine
1174 // did. Eventually it might make more sense to have the diagnostic engine
1175 // include some "why" information in the diagnostic.
1176
1177 // If this is a warning which has been mapped to an error by the user (as
1178 // inferred by checking whether the default mapping is to an error) then
1179 // flag it as such. Note that diagnostics could also have been mapped by a
1180 // pragma, but we don't currently have a way to distinguish this.
Chandler Carruth60740842011-09-26 00:44:09 +00001181 if (Level == DiagnosticsEngine::Error &&
Daniel Dunbaraa111382011-09-29 01:01:08 +00001182 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID()) &&
1183 !DiagnosticIDs::isDefaultMappingAsError(Info.getID())) {
1184 OS << " [-Werror";
1185 Started = true;
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001186 }
1187
1188 // If the diagnostic is an extension diagnostic and not enabled by default
1189 // then it must have been turned on with -pedantic.
1190 bool EnabledByDefault;
1191 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1192 EnabledByDefault) &&
1193 !EnabledByDefault) {
1194 OS << (Started ? "," : " [") << "-pedantic";
1195 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001196 }
1197
1198 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
1199 if (!Opt.empty()) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001200 OS << (Started ? "," : " [") << "-W" << Opt;
1201 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001202 }
1203 }
Chandler Carruth60740842011-09-26 00:44:09 +00001204
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001205 // If the user wants to see category information, include it too.
1206 if (DiagOpts.ShowCategories) {
1207 unsigned DiagCategory =
1208 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth60740842011-09-26 00:44:09 +00001209 if (DiagCategory) {
Chandler Carruth0059a9b2011-09-26 01:21:58 +00001210 OS << (Started ? "," : " [");
Benjamin Kramere2125d82011-09-26 02:14:13 +00001211 Started = true;
Chandler Carruth60740842011-09-26 00:44:09 +00001212 if (DiagOpts.ShowCategories == 1)
Benjamin Kramere2125d82011-09-26 02:14:13 +00001213 OS << DiagCategory;
Chandler Carruth60740842011-09-26 00:44:09 +00001214 else {
1215 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
1216 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
1217 }
1218 }
Chandler Carruth60740842011-09-26 00:44:09 +00001219 }
Benjamin Kramere2125d82011-09-26 02:14:13 +00001220 if (Started)
1221 OS << ']';
Chandler Carruth60740842011-09-26 00:44:09 +00001222}
1223
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001224void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +00001225 const Diagnostic &Info) {
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001226 // Default implementation (Warnings/errors count).
1227 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1228
Chandler Carruth2be992d2011-09-26 11:25:30 +00001229 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1230 // this later as we print out the diagnostic to the terminal.
1231 llvm::SmallString<100> OutStr;
1232 Info.FormatDiagnostic(OutStr);
1233
1234 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1235 if (DiagOpts->ShowNames)
1236 printDiagnosticName(DiagMessageStream, Info);
1237 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1238
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001239 // Keeps track of the the starting position of the location
1240 // information (e.g., "foo.c:10:4:") that precedes the error
1241 // message. We use this information to determine how long the
1242 // file+line+column number prefix is.
1243 uint64_t StartOfLocationInfo = OS.tell();
1244
1245 if (!Prefix.empty())
1246 OS << Prefix << ": ";
1247
Chandler Carruth2be992d2011-09-26 11:25:30 +00001248 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruth577372e2011-09-26 11:38:46 +00001249 // This is important as if the location is missing, we may be emitting
1250 // diagnostics in a context that lacks language options, a source manager, or
1251 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth2be992d2011-09-26 11:25:30 +00001252 if (!Info.getLocation().isValid()) {
1253 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
1254 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1255 OS.tell() - StartOfLocationInfo,
1256 DiagOpts->MessageLength, DiagOpts->ShowColors);
1257 OS.flush();
1258 return;
Chandler Carruth09c65ce2011-09-26 00:26:47 +00001259 }
1260
Chandler Carruth577372e2011-09-26 11:38:46 +00001261 // Assert that the rest of our infrastructure is setup properly.
1262 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1263 assert(DiagOpts && "Unexpected diagnostic without options set");
1264 assert(Info.hasSourceManager() &&
1265 "Unexpected diagnostic with no source manager");
Chandler Carruth2be992d2011-09-26 11:25:30 +00001266 const SourceManager &SM = Info.getSourceManager();
Chandler Carruth577372e2011-09-26 11:38:46 +00001267 TextDiagnostic TextDiag(*this, OS, SM, *LangOpts, *DiagOpts);
1268
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001269 TextDiag.Emit(Info.getLocation(), Level, DiagMessageStream.str(),
1270 Info.getRanges(),
1271 llvm::makeArrayRef(Info.getFixItHints(),
1272 Info.getNumFixItHints()),
1273 LastLoc, LastCaretDiagnosticWasNote);
Chandler Carruth2be992d2011-09-26 11:25:30 +00001274
Chandler Carruthc38c7b12011-10-15 11:09:19 +00001275 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
1276 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
1277 LastCaretDiagnosticWasNote = (Level == DiagnosticsEngine::Note);
Daniel Dunbar49f0e802009-09-07 23:07:56 +00001278
Chris Lattner327984f2008-11-19 06:56:25 +00001279 OS.flush();
Bill Wendling37b1dde2007-06-07 09:34:54 +00001280}
Douglas Gregord0e9e3a2011-09-29 00:38:00 +00001281
1282DiagnosticConsumer *
1283TextDiagnosticPrinter::clone(DiagnosticsEngine &Diags) const {
1284 return new TextDiagnosticPrinter(OS, *DiagOpts, /*OwnsOutputStream=*/false);
1285}