blob: b9987deaf681c88557ad853d1d6fb4b30f98c892 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
Axel Naumann04331162011-01-27 10:55:51 +000015#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/SourceManager.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000017#include "clang/Frontend/DiagnosticOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Lex/Lexer.h"
Chris Lattner037fb7f2009-05-05 22:03:18 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnera03a5b52008-11-19 06:56:25 +000020#include "llvm/Support/raw_ostream.h"
David Blaikie548f6c82011-09-23 05:57:42 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000022#include "llvm/ADT/SmallString.h"
Chris Lattnerc9b88902010-05-04 21:13:21 +000023#include "llvm/ADT/StringExtras.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000024#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Chris Lattner5f9e2722011-07-23 10:55:15 +000027static const enum raw_ostream::Colors noteColor =
28 raw_ostream::BLACK;
29static const enum raw_ostream::Colors fixitColor =
30 raw_ostream::GREEN;
31static const enum raw_ostream::Colors caretColor =
32 raw_ostream::GREEN;
33static const enum raw_ostream::Colors warningColor =
34 raw_ostream::MAGENTA;
35static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
36static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000037// Used for changing only the bold attribute.
Chris Lattner5f9e2722011-07-23 10:55:15 +000038static const enum raw_ostream::Colors savedColor =
39 raw_ostream::SAVEDCOLOR;
Torok Edwin603fca72009-06-04 07:18:23 +000040
Douglas Gregorfffd93f2009-05-01 21:53:04 +000041/// \brief Number of spaces to indent when word-wrapping.
42const unsigned WordWrapIndentation = 6;
43
Chris Lattner5f9e2722011-07-23 10:55:15 +000044TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000045 const DiagnosticOptions &diags,
46 bool _OwnsOutputStream)
Daniel Dunbareace8742009-11-04 06:24:30 +000047 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbaraea36412009-11-11 09:38:24 +000048 LastCaretDiagnosticWasNote(0),
49 OwnsOutputStream(_OwnsOutputStream) {
50}
51
52TextDiagnosticPrinter::~TextDiagnosticPrinter() {
53 if (OwnsOutputStream)
54 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000055}
56
Chandler Carruth0d6b8932011-08-31 23:59:19 +000057/// \brief Helper to recursivly walk up the include stack and print each layer
58/// on the way back down.
59static void PrintIncludeStackRecursively(raw_ostream &OS,
60 const SourceManager &SM,
61 SourceLocation Loc,
62 bool ShowLocation) {
63 if (Loc.isInvalid())
64 return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000065
Chris Lattnerb9c3f962009-01-27 07:57:44 +000066 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000067 if (PLoc.isInvalid())
68 return;
Chris Lattner5ce24c82009-04-21 03:57:54 +000069
Chandler Carruth0d6b8932011-08-31 23:59:19 +000070 // Print out the other include frames first.
71 PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
72
73 if (ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000074 OS << "In file included from " << PLoc.getFilename()
75 << ':' << PLoc.getLine() << ":\n";
76 else
77 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000078}
79
Chandler Carruth0d6b8932011-08-31 23:59:19 +000080/// \brief Prints an include stack when appropriate for a particular diagnostic
81/// level and location.
82///
83/// This routine handles all the logic of suppressing particular include stacks
84/// (such as those for notes) and duplicate include stacks when repeated
85/// warnings occur within the same file. It also handles the logic of
86/// customizing the formatting and display of the include stack.
87///
88/// \param Level The diagnostic level of the message this stack pertains to.
89/// \param Loc The include location of the current file (not the diagnostic
90/// location).
91void TextDiagnosticPrinter::PrintIncludeStack(Diagnostic::Level Level,
92 SourceLocation Loc,
93 const SourceManager &SM) {
94 // Skip redundant include stacks altogether.
95 if (LastWarningLoc == Loc)
96 return;
97 LastWarningLoc = Loc;
98
99 if (!DiagOpts->ShowNoteIncludeStack && Level == Diagnostic::Note)
100 return;
101
102 PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
103}
104
Douglas Gregor47f71772009-05-01 23:32:58 +0000105/// \brief When the source code line we want to print is too long for
106/// the terminal, select the "interesting" region.
107static void SelectInterestingSourceRegion(std::string &SourceLine,
108 std::string &CaretLine,
109 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000110 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000111 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000112 unsigned MaxSize = std::max(SourceLine.size(),
113 std::max(CaretLine.size(),
114 FixItInsertionLine.size()));
115 if (MaxSize > SourceLine.size())
116 SourceLine.resize(MaxSize, ' ');
117 if (MaxSize > CaretLine.size())
118 CaretLine.resize(MaxSize, ' ');
119 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
120 FixItInsertionLine.resize(MaxSize, ' ');
121
Douglas Gregor47f71772009-05-01 23:32:58 +0000122 // Find the slice that we need to display the full caret line
123 // correctly.
124 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
125 for (; CaretStart != CaretEnd; ++CaretStart)
126 if (!isspace(CaretLine[CaretStart]))
127 break;
128
129 for (; CaretEnd != CaretStart; --CaretEnd)
130 if (!isspace(CaretLine[CaretEnd - 1]))
131 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000132
133 // Make sure we don't chop the string shorter than the caret token
134 // itself.
135 if (CaretEnd < EndOfCaretToken)
136 CaretEnd = EndOfCaretToken;
137
Douglas Gregor844da342009-05-03 04:33:32 +0000138 // If we have a fix-it line, make sure the slice includes all of the
139 // fix-it information.
140 if (!FixItInsertionLine.empty()) {
141 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
142 for (; FixItStart != FixItEnd; ++FixItStart)
143 if (!isspace(FixItInsertionLine[FixItStart]))
144 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000145
Douglas Gregor844da342009-05-03 04:33:32 +0000146 for (; FixItEnd != FixItStart; --FixItEnd)
147 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
148 break;
149
150 if (FixItStart < CaretStart)
151 CaretStart = FixItStart;
152 if (FixItEnd > CaretEnd)
153 CaretEnd = FixItEnd;
154 }
155
Douglas Gregor47f71772009-05-01 23:32:58 +0000156 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
157 // parts of the caret line. While this slice is smaller than the
158 // number of columns we have, try to grow the slice to encompass
159 // more context.
160
161 // If the end of the interesting region comes before we run out of
162 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000163 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000164 CaretStart = 0;
165
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000166 unsigned TargetColumns = Columns;
167 if (TargetColumns > 8)
168 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000169 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000170 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000171 bool ExpandedRegion = false;
172 // Move the start of the interesting region left until we've
173 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000174 if (CaretStart == 1)
175 CaretStart = 0;
176 else if (CaretStart > 1) {
177 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000178
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000179 // Skip over any whitespace we see here; we're looking for
180 // another bit of interesting text.
181 while (NewStart && isspace(SourceLine[NewStart]))
182 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000183
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000184 // Skip over this bit of "interesting" text.
185 while (NewStart && !isspace(SourceLine[NewStart]))
186 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000187
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000188 // Move up to the non-whitespace character we just saw.
189 if (NewStart)
190 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000191
192 // If we're still within our limit, update the starting
193 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000194 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000195 CaretStart = NewStart;
196 ExpandedRegion = true;
197 }
198 }
199
200 // Move the end of the interesting region right until we've
201 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000202 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000203 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000204 unsigned NewEnd = CaretEnd;
205
206 // Skip over any whitespace we see here; we're looking for
207 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000208 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000209 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000210
Douglas Gregor47f71772009-05-01 23:32:58 +0000211 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000212 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000213 ++NewEnd;
214
215 if (NewEnd - CaretStart <= TargetColumns) {
216 CaretEnd = NewEnd;
217 ExpandedRegion = true;
218 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000219 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000220
221 if (!ExpandedRegion)
222 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000223 }
224
225 // [CaretStart, CaretEnd) is the slice we want. Update the various
226 // output lines to show only this slice, with two-space padding
227 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000228 if (CaretEnd < SourceLine.size())
229 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000230 if (CaretEnd < CaretLine.size())
231 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000232 if (FixItInsertionLine.size() > CaretEnd)
233 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000234
Douglas Gregor47f71772009-05-01 23:32:58 +0000235 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000236 SourceLine.replace(0, CaretStart, " ...");
237 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000238 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000239 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000240 }
241}
242
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000243/// Look through spelling locations for a macro argument expansion, and
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000244/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000245/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000246/// don't skip anything and return the starting location.
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000247static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000248 SourceLocation StartLoc) {
249 for (SourceLocation L = StartLoc; L.isMacroID();
250 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruth96d35892011-07-26 03:03:00 +0000251 if (SM.isMacroArgExpansion(L))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000252 return L;
253 }
254
255 // Otherwise just return initial location, there's nothing to skip.
256 return StartLoc;
257}
258
259/// Gets the location of the immediate macro caller, one level up the stack
260/// toward the initial macro typed into the source.
261static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
262 SourceLocation Loc) {
263 if (!Loc.isMacroID()) return Loc;
264
265 // When we have the location of (part of) an expanded parameter, its spelling
266 // location points to the argument as typed into the macro call, and
267 // therefore is used to locate the macro caller.
Chandler Carruth96d35892011-07-26 03:03:00 +0000268 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000269 return SM.getImmediateSpellingLoc(Loc);
270
271 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000272 // expanded (while the spelling is part of the macro definition).
Chandler Carruth999f7392011-07-25 20:52:21 +0000273 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000274}
275
276/// Gets the location of the immediate macro callee, one level down the stack
277/// toward the leaf macro.
278static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
279 SourceLocation Loc) {
280 if (!Loc.isMacroID()) return Loc;
281
282 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000283 // expansion location points to the unexpanded paramater reference within
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000284 // the macro definition (or callee).
Chandler Carruth96d35892011-07-26 03:03:00 +0000285 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth999f7392011-07-25 20:52:21 +0000286 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000287
288 // Otherwise, the callee of the macro is located where this location was
289 // spelled inside the macro definition.
290 return SM.getImmediateSpellingLoc(Loc);
291}
292
Chandler Carruth50c909b2011-08-31 23:59:23 +0000293namespace {
294
295/// \brief Class to encapsulate the logic for printing a caret diagnostic
296/// message.
297///
298/// This class provides an interface for building and emitting a caret
299/// diagnostic, including all of the macro backtrace caret diagnostics, FixIt
300/// Hints, and code snippets. In the presence of macros this turns into
301/// a recursive process and so the class provides common state across the
302/// emission of a particular diagnostic, while each invocation of \see Emit()
303/// walks down the macro stack.
304///
305/// This logic assumes that the core diagnostic location and text has already
306/// been emitted and focuses on emitting the pretty caret display and macro
307/// backtrace following that.
308///
309/// FIXME: Hoist helper routines specific to caret diagnostics into class
310/// methods to reduce paramater passing churn.
311class CaretDiagnostic {
312 TextDiagnosticPrinter &Printer;
313 raw_ostream &OS;
314 const SourceManager &SM;
315 const LangOptions &LangOpts;
316 const DiagnosticOptions &DiagOpts;
317 const unsigned Columns, MacroSkipStart, MacroSkipEnd;
318
319public:
320 CaretDiagnostic(TextDiagnosticPrinter &Printer,
321 raw_ostream &OS,
322 const SourceManager &SM,
323 const LangOptions &LangOpts,
324 const DiagnosticOptions &DiagOpts,
325 unsigned Columns,
326 unsigned MacroSkipStart,
327 unsigned MacroSkipEnd)
328 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
329 Columns(Columns), MacroSkipStart(MacroSkipStart),
330 MacroSkipEnd(MacroSkipEnd) {
331 }
332
333 /// \brief Emit the caret diagnostic text.
334 ///
335 /// Walks up the macro expansion stack printing the code snippet, caret,
336 /// underlines and FixItHint display as appropriate at each level. Walk is
337 /// accomplished by calling itself recursively.
338 ///
Chandler Carruth50c909b2011-08-31 23:59:23 +0000339 /// FIXME: Break up massive function into logical units.
340 ///
341 /// \param Loc The location for this caret.
342 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000343 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000344 /// \param OnMacroInst The current depth of the macro expansion stack.
345 void Emit(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000346 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000347 ArrayRef<FixItHint> Hints,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000348 unsigned OnMacroInst = 0) {
349 assert(!Loc.isInvalid() && "must have a valid source location here");
350
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000351 // If this is a file source location, directly emit the source snippet and
352 // caret line.
353 if (Loc.isFileID())
354 return EmitSnippetAndCaret(Loc, Ranges, Hints);
355 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000356
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000357 // Whether to suppress printing this macro expansion.
358 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
359 OnMacroInst < MacroSkipEnd);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000360
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000361 // When processing macros, skip over the expansions leading up to
362 // a macro argument, and trace the argument's expansion stack instead.
363 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000364
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000365 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000366
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000367 // FIXME: Map ranges?
368 Emit(OneLevelUp, Ranges, Hints, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000369
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000370 // Map the location.
371 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000372
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000373 // Map the ranges.
374 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
375 E = Ranges.end();
376 I != E; ++I) {
377 SourceLocation Start = I->getBegin(), End = I->getEnd();
378 if (Start.isMacroID())
379 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
380 if (End.isMacroID())
381 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
382 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000383
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000384 if (!Suppressed) {
385 // Don't print recursive expansion notes from an expansion note.
386 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000387
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000388 // Get the pretty name, according to #line directives etc.
389 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
390 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000391 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000392
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000393 // If this diagnostic is not in the main file, print out the
394 // "included from" lines.
395 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000396
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000397 if (DiagOpts.ShowLocation) {
398 // Emit the file/line/column that this expansion came from.
399 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
400 if (DiagOpts.ShowColumn)
401 OS << PLoc.getColumn() << ':';
402 OS << ' ';
403 }
404 OS << "note: expanded from:\n";
405
406 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000407 return;
408 }
409
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000410 if (OnMacroInst == MacroSkipStart) {
411 // Tell the user that we've skipped contexts.
412 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
413 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
414 "all)\n";
415 }
416 }
417
418 /// \brief Emit a code snippet and caret line.
419 ///
420 /// This routine emits a single line's code snippet and caret line..
421 ///
422 /// \param Loc The location for the caret.
423 /// \param Ranges The underlined ranges for this code snippet.
424 /// \param Hints The FixIt hints active for this diagnostic.
425 void EmitSnippetAndCaret(SourceLocation Loc,
426 SmallVectorImpl<CharSourceRange>& Ranges,
427 ArrayRef<FixItHint> Hints) {
428 assert(!Loc.isInvalid() && "must have a valid source location here");
429 assert(Loc.isFileID() && "must have a file location here");
430
Chandler Carruth50c909b2011-08-31 23:59:23 +0000431 // Decompose the location into a FID/Offset pair.
432 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
433 FileID FID = LocInfo.first;
434 unsigned FileOffset = LocInfo.second;
435
436 // Get information about the buffer it points into.
437 bool Invalid = false;
438 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
439 if (Invalid)
440 return;
441
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000442 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000443 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
444 unsigned CaretEndColNo
445 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
446
447 // Rewind from the current position to the start of the line.
448 const char *TokPtr = BufStart+FileOffset;
449 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
450
451
452 // Compute the line end. Scan forward from the error position to the end of
453 // the line.
454 const char *LineEnd = TokPtr;
455 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
456 ++LineEnd;
457
458 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
459 // the source line length as currently being computed. See
460 // test/Misc/message-length.c.
461 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
462
463 // Copy the line of code into an std::string for ease of manipulation.
464 std::string SourceLine(LineStart, LineEnd);
465
466 // Create a line for the caret that is filled with spaces that is the same
467 // length as the line of source code.
468 std::string CaretLine(LineEnd-LineStart, ' ');
469
470 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000471 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
472 E = Ranges.end();
473 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000474 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000475
476 // Next, insert the caret itself.
477 if (ColNo-1 < CaretLine.size())
478 CaretLine[ColNo-1] = '^';
479 else
480 CaretLine.push_back('^');
481
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000482 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000483
484 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
485 // to produce easily machine parsable output. Add a space before the
486 // source line and the caret to make it trivial to tell the main diagnostic
487 // line from what the user is intended to see.
488 if (DiagOpts.ShowSourceRanges) {
489 SourceLine = ' ' + SourceLine;
490 CaretLine = ' ' + CaretLine;
491 }
492
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000493 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000494 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000495 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000496
497 // If the source line is too long for our terminal, select only the
498 // "interesting" source region within that line.
499 if (Columns && SourceLine.size() > Columns)
500 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
501 CaretEndColNo, Columns);
502
503 // Finally, remove any blank spaces from the end of CaretLine.
504 while (CaretLine[CaretLine.size()-1] == ' ')
505 CaretLine.erase(CaretLine.end()-1);
506
507 // Emit what we have computed.
508 OS << SourceLine << '\n';
509
510 if (DiagOpts.ShowColors)
511 OS.changeColor(caretColor, true);
512 OS << CaretLine << '\n';
513 if (DiagOpts.ShowColors)
514 OS.resetColor();
515
516 if (!FixItInsertionLine.empty()) {
517 if (DiagOpts.ShowColors)
518 // Print fixit line in color
519 OS.changeColor(fixitColor, false);
520 if (DiagOpts.ShowSourceRanges)
521 OS << ' ';
522 OS << FixItInsertionLine << '\n';
523 if (DiagOpts.ShowColors)
524 OS.resetColor();
525 }
526
Chandler Carruthcca61582011-09-02 06:30:30 +0000527 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000528 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000529 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000530
Chandler Carruthcca61582011-09-02 06:30:30 +0000531private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000532 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
533 void HighlightRange(const CharSourceRange &R,
534 unsigned LineNo, FileID FID,
535 const std::string &SourceLine,
536 std::string &CaretLine) {
537 assert(CaretLine.size() == SourceLine.size() &&
538 "Expect a correspondence between source and caret line!");
539 if (!R.isValid()) return;
540
541 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
542 SourceLocation End = SM.getExpansionLoc(R.getEnd());
543
544 // If the End location and the start location are the same and are a macro
545 // location, then the range was something that came from a macro expansion
546 // or _Pragma. If this is an object-like macro, the best we can do is to
547 // highlight the range. If this is a function-like macro, we'd also like to
548 // highlight the arguments.
549 if (Begin == End && R.getEnd().isMacroID())
550 End = SM.getExpansionRange(R.getEnd()).second;
551
552 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
553 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
554 return; // No intersection.
555
556 unsigned EndLineNo = SM.getExpansionLineNumber(End);
557 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
558 return; // No intersection.
559
560 // Compute the column number of the start.
561 unsigned StartColNo = 0;
562 if (StartLineNo == LineNo) {
563 StartColNo = SM.getExpansionColumnNumber(Begin);
564 if (StartColNo) --StartColNo; // Zero base the col #.
565 }
566
567 // Compute the column number of the end.
568 unsigned EndColNo = CaretLine.size();
569 if (EndLineNo == LineNo) {
570 EndColNo = SM.getExpansionColumnNumber(End);
571 if (EndColNo) {
572 --EndColNo; // Zero base the col #.
573
574 // Add in the length of the token, so that we cover multi-char tokens if
575 // this is a token range.
576 if (R.isTokenRange())
577 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
578 } else {
579 EndColNo = CaretLine.size();
580 }
581 }
582
583 assert(StartColNo <= EndColNo && "Invalid range!");
584
585 // Check that a token range does not highlight only whitespace.
586 if (R.isTokenRange()) {
587 // Pick the first non-whitespace column.
588 while (StartColNo < SourceLine.size() &&
589 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
590 ++StartColNo;
591
592 // Pick the last non-whitespace column.
593 if (EndColNo > SourceLine.size())
594 EndColNo = SourceLine.size();
595 while (EndColNo-1 &&
596 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
597 --EndColNo;
598
599 // If the start/end passed each other, then we are trying to highlight a
600 // range that just exists in whitespace, which must be some sort of other
601 // bug.
602 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
603 }
604
605 // Fill the range with ~'s.
606 for (unsigned i = StartColNo; i < EndColNo; ++i)
607 CaretLine[i] = '~';
608 }
609
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000610 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000611 const char *LineStart,
612 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000613 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000614 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000615 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000616 return FixItInsertionLine;
617
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000618 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
619 I != E; ++I) {
620 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000621 // We have an insertion hint. Determine whether the inserted
622 // code is on the same line as the caret.
623 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000624 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000625 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000626 // Insert the new code into the line just below the code
627 // that the user wrote.
628 unsigned HintColNo
629 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
630 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000631 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000632 if (LastColumnModified > FixItInsertionLine.size())
633 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000634 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000635 FixItInsertionLine.begin() + HintColNo - 1);
636 } else {
637 FixItInsertionLine.clear();
638 break;
639 }
640 }
641 }
642
643 if (FixItInsertionLine.empty())
644 return FixItInsertionLine;
645
646 // Now that we have the entire fixit line, expand the tabs in it.
647 // Since we don't want to insert spaces in the middle of a word,
648 // find each word and the column it should line up with and insert
649 // spaces until they match.
650 unsigned FixItPos = 0;
651 unsigned LinePos = 0;
652 unsigned TabExpandedCol = 0;
653 unsigned LineLength = LineEnd - LineStart;
654
655 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
656 // Find the next word in the FixIt line.
657 while (FixItPos < FixItInsertionLine.size() &&
658 FixItInsertionLine[FixItPos] == ' ')
659 ++FixItPos;
660 unsigned CharDistance = FixItPos - TabExpandedCol;
661
662 // Walk forward in the source line, keeping track of
663 // the tab-expanded column.
664 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
665 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
666 ++TabExpandedCol;
667 else
668 TabExpandedCol =
669 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
670
671 // Adjust the fixit line to match this column.
672 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
673 FixItPos = TabExpandedCol;
674
675 // Walk to the end of the word.
676 while (FixItPos < FixItInsertionLine.size() &&
677 FixItInsertionLine[FixItPos] != ' ')
678 ++FixItPos;
679 }
680
681 return FixItInsertionLine;
682 }
683
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000684 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
685 // Scan the source line, looking for tabs. If we find any, manually expand
686 // them to spaces and update the CaretLine to match.
687 for (unsigned i = 0; i != SourceLine.size(); ++i) {
688 if (SourceLine[i] != '\t') continue;
689
690 // Replace this tab with at least one space.
691 SourceLine[i] = ' ';
692
693 // Compute the number of spaces we need to insert.
694 unsigned TabStop = DiagOpts.TabStop;
695 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
696 "Invalid -ftabstop value");
697 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
698 assert(NumSpaces < TabStop && "Invalid computation of space amt");
699
700 // Insert spaces into the SourceLine.
701 SourceLine.insert(i+1, NumSpaces, ' ');
702
703 // Insert spaces or ~'s into CaretLine.
704 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
705 }
706 }
707
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000708 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000709 if (!DiagOpts.ShowParseableFixits)
710 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000711
Chandler Carruthcca61582011-09-02 06:30:30 +0000712 // We follow FixItRewriter's example in not (yet) handling
713 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000714 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
715 I != E; ++I) {
716 if (I->RemoveRange.isInvalid() ||
717 I->RemoveRange.getBegin().isMacroID() ||
718 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000719 return;
720 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000721
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000722 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
723 I != E; ++I) {
724 SourceLocation BLoc = I->RemoveRange.getBegin();
725 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000726
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000727 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
728 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000729
Chandler Carruthcca61582011-09-02 06:30:30 +0000730 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000731 if (I->RemoveRange.isTokenRange())
732 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000733
Chandler Carruthcca61582011-09-02 06:30:30 +0000734 // We specifically do not do word-wrapping or tab-expansion here,
735 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000736 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000737 if (PLoc.isInvalid())
738 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000739
Chandler Carruthcca61582011-09-02 06:30:30 +0000740 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000741 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000742 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
743 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
744 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
745 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
746 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000747 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000748 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000749 }
750 }
751};
752
753} // end namespace
754
Chandler Carruth5182a182011-09-07 01:47:09 +0000755void TextDiagnosticPrinter::EmitCaretDiagnostic(
756 SourceLocation Loc,
757 SmallVectorImpl<CharSourceRange>& Ranges,
758 const SourceManager &SM,
759 ArrayRef<FixItHint> Hints,
760 unsigned Columns,
761 unsigned MacroSkipStart,
762 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000763 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chandler Carruth50c909b2011-08-31 23:59:23 +0000764 assert(DiagOpts && "Unexpected diagnostic without options set");
765 // FIXME: Remove this method and have clients directly build and call Emit on
766 // the CaretDiagnostic object.
767 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts,
768 Columns, MacroSkipStart, MacroSkipEnd);
Chandler Carruth5182a182011-09-07 01:47:09 +0000769 CaretDiag.Emit(Loc, Ranges, Hints);
Chris Lattner94f55782009-02-17 07:38:37 +0000770}
771
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000772/// \brief Skip over whitespace in the string, starting at the given
773/// index.
774///
775/// \returns The index of the first non-whitespace character that is
776/// greater than or equal to Idx or, if no such character exists,
777/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000778static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000779 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000780 unsigned Length) {
781 while (Idx < Length && isspace(Str[Idx]))
782 ++Idx;
783 return Idx;
784}
785
786/// \brief If the given character is the start of some kind of
787/// balanced punctuation (e.g., quotes or parentheses), return the
788/// character that will terminate the punctuation.
789///
790/// \returns The ending punctuation character, if any, or the NULL
791/// character if the input character does not start any punctuation.
792static inline char findMatchingPunctuation(char c) {
793 switch (c) {
794 case '\'': return '\'';
795 case '`': return '\'';
796 case '"': return '"';
797 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000798 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000799 case '{': return '}';
800 default: break;
801 }
802
803 return 0;
804}
805
806/// \brief Find the end of the word starting at the given offset
807/// within a string.
808///
809/// \returns the index pointing one character past the end of the
810/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000811static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000812 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000813 unsigned Length, unsigned Column,
814 unsigned Columns) {
815 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000816 unsigned End = Start + 1;
817
Daniel Dunbareae18f82009-12-06 09:56:18 +0000818 // If we are already at the end of the string, take that as the word.
819 if (End == Str.size())
820 return End;
821
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000822 // Determine if the start of the string is actually opening
823 // punctuation, e.g., a quote or parentheses.
824 char EndPunct = findMatchingPunctuation(Str[Start]);
825 if (!EndPunct) {
826 // This is a normal word. Just find the first space character.
827 while (End < Length && !isspace(Str[End]))
828 ++End;
829 return End;
830 }
831
832 // We have the start of a balanced punctuation sequence (quotes,
833 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000834 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000835 PunctuationEndStack.push_back(EndPunct);
836 while (End < Length && !PunctuationEndStack.empty()) {
837 if (Str[End] == PunctuationEndStack.back())
838 PunctuationEndStack.pop_back();
839 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
840 PunctuationEndStack.push_back(SubEndPunct);
841
842 ++End;
843 }
844
845 // Find the first space character after the punctuation ended.
846 while (End < Length && !isspace(Str[End]))
847 ++End;
848
849 unsigned PunctWordLength = End - Start;
850 if (// If the word fits on this line
851 Column + PunctWordLength <= Columns ||
852 // ... or the word is "short enough" to take up the next line
853 // without too much ugly white space
854 PunctWordLength < Columns/3)
855 return End; // Take the whole thing as a single "word".
856
857 // The whole quoted/parenthesized string is too long to print as a
858 // single "word". Instead, find the "word" that starts just after
859 // the punctuation and use that end-point instead. This will recurse
860 // until it finds something small enough to consider a word.
861 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
862}
863
864/// \brief Print the given string to a stream, word-wrapping it to
865/// some number of columns in the process.
866///
867/// \brief OS the stream to which the word-wrapping string will be
868/// emitted.
869///
870/// \brief Str the string to word-wrap and output.
871///
872/// \brief Columns the number of columns to word-wrap to.
873///
874/// \brief Column the column number at which the first character of \p
875/// Str will be printed. This will be non-zero when part of the first
876/// line has already been printed.
877///
878/// \brief Indentation the number of spaces to indent any lines beyond
879/// the first line.
880///
881/// \returns true if word-wrapping was required, or false if the
882/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000883static bool PrintWordWrapped(raw_ostream &OS,
884 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000885 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000886 unsigned Column = 0,
887 unsigned Indentation = WordWrapIndentation) {
888 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000889
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000890 // If there is a newline in this message somewhere, find that
891 // newline and split the message into the part before the newline
892 // (which will be word-wrapped) and the part from the newline one
893 // (which will be emitted unchanged).
894 for (unsigned I = 0; I != Length; ++I)
895 if (Str[I] == '\n') {
896 Length = I;
897 break;
898 }
899
900 // The string used to indent each line.
901 llvm::SmallString<16> IndentStr;
902 IndentStr.assign(Indentation, ' ');
903 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000904 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000905 WordStart = WordEnd) {
906 // Find the beginning of the next word.
907 WordStart = skipWhitespace(WordStart, Str, Length);
908 if (WordStart == Length)
909 break;
910
911 // Find the end of this word.
912 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000913
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000914 // Does this word fit on the current line?
915 unsigned WordLength = WordEnd - WordStart;
916 if (Column + WordLength < Columns) {
917 // This word fits on the current line; print it there.
918 if (WordStart) {
919 OS << ' ';
920 Column += 1;
921 }
922 OS.write(&Str[WordStart], WordLength);
923 Column += WordLength;
924 continue;
925 }
926
927 // This word does not fit on the current line, so wrap to the next
928 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000929 OS << '\n';
930 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000931 OS.write(&Str[WordStart], WordLength);
932 Column = Indentation + WordLength;
933 Wrapped = true;
934 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000935
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000936 if (Length == Str.size())
937 return Wrapped; // We're done.
938
939 // There is a newline in the message, followed by something that
940 // will not be word-wrapped. Print that.
941 OS.write(&Str[Length], Str.size() - Length);
942 return true;
943}
Chris Lattner94f55782009-02-17 07:38:37 +0000944
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000945/// Get the presumed location of a diagnostic message. This computes the
946/// presumed location for the top of any macro backtrace when present.
947static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
948 SourceLocation Loc) {
949 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
950 // walk to the top of the macro call stack.
951 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000952 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000953 Loc = getImmediateMacroCallerLoc(SM, Loc);
954 }
955
956 return SM.getPresumedLoc(Loc);
957}
958
Chandler Carruth5770bb72011-09-07 08:05:58 +0000959/// \brief Print out the file/line/column information and include trace.
960///
961/// This method handlen the emission of the diagnostic location information.
962/// This includes extracting as much location information as is present for the
963/// diagnostic and printing it, as well as any include stack or source ranges
964/// necessary.
965void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
966 const DiagnosticInfo &Info,
967 const SourceManager &SM,
968 PresumedLoc PLoc) {
969 if (PLoc.isInvalid()) {
970 // At least print the file name if available:
971 FileID FID = SM.getFileID(Info.getLocation());
972 if (!FID.isInvalid()) {
973 const FileEntry* FE = SM.getFileEntryForID(FID);
974 if (FE && FE->getName()) {
975 OS << FE->getName();
976 if (FE->getDevice() == 0 && FE->getInode() == 0
977 && FE->getFileMode() == 0) {
978 // in PCH is a guess, but a good one:
979 OS << " (in PCH)";
980 }
981 OS << ": ";
982 }
983 }
984 return;
985 }
986 unsigned LineNo = PLoc.getLine();
987
988 if (!DiagOpts->ShowLocation)
989 return;
990
991 if (DiagOpts->ShowColors)
992 OS.changeColor(savedColor, true);
993
994 OS << PLoc.getFilename();
995 switch (DiagOpts->Format) {
996 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
997 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
998 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
999 }
1000
1001 if (DiagOpts->ShowColumn)
1002 // Compute the column number.
1003 if (unsigned ColNo = PLoc.getColumn()) {
1004 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
1005 OS << ',';
1006 ColNo--;
1007 } else
1008 OS << ':';
1009 OS << ColNo;
1010 }
1011 switch (DiagOpts->Format) {
1012 case DiagnosticOptions::Clang:
1013 case DiagnosticOptions::Vi: OS << ':'; break;
1014 case DiagnosticOptions::Msvc: OS << ") : "; break;
1015 }
1016
1017 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1018 FileID CaretFileID =
1019 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1020 bool PrintedRange = false;
1021
1022 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1023 // Ignore invalid ranges.
1024 if (!Info.getRange(i).isValid()) continue;
1025
1026 SourceLocation B = Info.getRange(i).getBegin();
1027 SourceLocation E = Info.getRange(i).getEnd();
1028 B = SM.getExpansionLoc(B);
1029 E = SM.getExpansionLoc(E);
1030
1031 // If the End location and the start location are the same and are a
1032 // macro location, then the range was something that came from a
1033 // macro expansion or _Pragma. If this is an object-like macro, the
1034 // best we can do is to highlight the range. If this is a
1035 // function-like macro, we'd also like to highlight the arguments.
1036 if (B == E && Info.getRange(i).getEnd().isMacroID())
1037 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1038
1039 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1040 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1041
1042 // If the start or end of the range is in another file, just discard
1043 // it.
1044 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1045 continue;
1046
1047 // Add in the length of the token, so that we cover multi-char
1048 // tokens.
1049 unsigned TokSize = 0;
1050 if (Info.getRange(i).isTokenRange())
1051 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1052
1053 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1054 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1055 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1056 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1057 << '}';
1058 PrintedRange = true;
1059 }
1060
1061 if (PrintedRange)
1062 OS << ':';
1063 }
1064 OS << ' ';
1065}
1066
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001067void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +00001068 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +00001069 // Default implementation (Warnings/errors count).
1070 DiagnosticClient::HandleDiagnostic(Level, Info);
1071
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001072 // Keeps track of the the starting position of the location
1073 // information (e.g., "foo.c:10:4:") that precedes the error
1074 // message. We use this information to determine how long the
1075 // file+line+column number prefix is.
1076 uint64_t StartOfLocationInfo = OS.tell();
1077
Daniel Dunbarb96b6702010-02-25 03:23:40 +00001078 if (!Prefix.empty())
1079 OS << Prefix << ": ";
1080
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001081 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001082 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001083 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001084
Chandler Carruth5770bb72011-09-07 08:05:58 +00001085 // First, if this diagnostic is not in the main file, print out the
1086 // "included from" lines.
1087 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1088 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +00001089
Chandler Carruth5770bb72011-09-07 08:05:58 +00001090 // Next emit the location of this particular diagnostic.
1091 EmitDiagnosticLoc(Level, Info, SM, PLoc);
Axel Naumann04331162011-01-27 10:55:51 +00001092
Chandler Carruth5770bb72011-09-07 08:05:58 +00001093 if (DiagOpts->ShowColors)
1094 OS.resetColor();
Torok Edwin603fca72009-06-04 07:18:23 +00001095 }
1096
Daniel Dunbareace8742009-11-04 06:24:30 +00001097 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001098 // Print diagnostic category in bold and color
1099 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001100 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Torok Edwin603fca72009-06-04 07:18:23 +00001101 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1102 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1103 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1104 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001105 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001107
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001109 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001110 case Diagnostic::Note: OS << "note: "; break;
1111 case Diagnostic::Warning: OS << "warning: "; break;
1112 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001113 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 }
Torok Edwin603fca72009-06-04 07:18:23 +00001115
Daniel Dunbareace8742009-11-04 06:24:30 +00001116 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001117 OS.resetColor();
1118
Chris Lattnerf4c83962008-11-19 06:51:40 +00001119 llvm::SmallString<100> OutStr;
1120 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001121
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001122 if (DiagOpts->ShowNames &&
1123 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1124 OutStr += " [";
1125 OutStr += DiagnosticIDs::getName(Info.getID());
1126 OutStr += "]";
1127 }
1128
Chris Lattnerc9b88902010-05-04 21:13:21 +00001129 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001130 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001131 // Was this a warning mapped to an error using -Werror or pragma?
1132 if (Level == Diagnostic::Error &&
1133 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1134 diag::Mapping mapping = diag::MAP_IGNORE;
1135 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1136 &mapping);
1137 if (mapping == diag::MAP_WARNING)
1138 OptionName += "-Werror";
1139 }
1140
Chris Lattner5f9e2722011-07-23 10:55:15 +00001141 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001142 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001143 if (!OptionName.empty())
1144 OptionName += ',';
1145 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001146 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001147 } else if (Info.getID() == diag::fatal_too_many_errors) {
1148 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001149 } else {
1150 // If the diagnostic is an extension diagnostic and not enabled by default
1151 // then it must have been turned on with -pedantic.
1152 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001153 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1154 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001155 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001156 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001157 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001158 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001159
1160 // If the user wants to see category information, include it too.
1161 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001162 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001163 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001164
Chris Lattnerc9b88902010-05-04 21:13:21 +00001165 // If there is any categorization information, include it.
1166 if (!OptionName.empty() || DiagCategory != 0) {
1167 bool NeedsComma = false;
1168 OutStr += " [";
1169
1170 if (!OptionName.empty()) {
1171 OutStr += OptionName;
1172 NeedsComma = true;
1173 }
1174
1175 if (DiagCategory) {
1176 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001177 if (DiagOpts->ShowCategories == 1)
1178 OutStr += llvm::utostr(DiagCategory);
1179 else {
1180 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001181 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001182 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001183 }
1184
1185 OutStr += "]";
1186 }
1187
1188
Daniel Dunbareace8742009-11-04 06:24:30 +00001189 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001190 // Print warnings, errors and fatal errors in bold, no color
1191 switch (Level) {
1192 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1193 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1194 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1195 default: break; //don't bold notes
1196 }
1197 }
1198
Daniel Dunbareace8742009-11-04 06:24:30 +00001199 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001200 // We will be word-wrapping the error message, so compute the
1201 // column number where we currently are (after printing the
1202 // location information).
1203 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001204 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001205 } else {
1206 OS.write(OutStr.begin(), OutStr.size());
1207 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001208 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001209 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001210 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001211
Douglas Gregordf667e72009-03-10 20:44:00 +00001212 // If caret diagnostics are enabled and we have location, we want to
1213 // emit the caret. However, we only do this if the location moved
1214 // from the last diagnostic, if the last diagnostic was a note that
1215 // was part of a different warning or error diagnostic, or if the
1216 // diagnostic has ranges. We don't want to emit the same caret
1217 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001218 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001219 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001220 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001221 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001222 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001223 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001224 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001225
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001226 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001227 SmallVector<CharSourceRange, 20> Ranges;
1228 Ranges.reserve(Info.getNumRanges());
1229 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1230 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001231
Chandler Carruth5182a182011-09-07 01:47:09 +00001232 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001233 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001234 if (Hint.RemoveRange.isValid())
1235 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001236 }
1237
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001238 const SourceManager &SM = LastLoc.getManager();
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001239 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1240 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001241 // Compute the length of the macro-expansion backtrace, so that we
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001242 // can establish which steps in the macro backtrace we'll skip.
1243 SourceLocation Loc = LastLoc;
1244 unsigned Depth = 0;
1245 do {
1246 ++Depth;
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001247 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001248 Loc = getImmediateMacroCallerLoc(SM, Loc);
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001249 } while (!Loc.isFileID());
1250
1251 if (Depth > DiagOpts->MacroBacktraceLimit) {
1252 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1253 DiagOpts->MacroBacktraceLimit % 2;
1254 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1255 }
1256 }
1257
Chandler Carruth5182a182011-09-07 01:47:09 +00001258 EmitCaretDiagnostic(LastLoc, Ranges, LastLoc.getManager(),
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001259 llvm::makeArrayRef(Info.getFixItHints(),
1260 Info.getNumFixItHints()),
Chandler Carruth50c909b2011-08-31 23:59:23 +00001261 DiagOpts->MessageLength,
1262 MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001263 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001264
Chris Lattnera03a5b52008-11-19 06:56:25 +00001265 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001266}