blob: ca060b6d66a9ae17d1958beeb5a69646acfc7b89 [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;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000317
318public:
319 CaretDiagnostic(TextDiagnosticPrinter &Printer,
320 raw_ostream &OS,
321 const SourceManager &SM,
322 const LangOptions &LangOpts,
Chandler Carruth8be5c152011-09-25 22:31:58 +0000323 const DiagnosticOptions &DiagOpts)
324 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts) {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000325 }
326
327 /// \brief Emit the caret diagnostic text.
328 ///
329 /// Walks up the macro expansion stack printing the code snippet, caret,
330 /// underlines and FixItHint display as appropriate at each level. Walk is
331 /// accomplished by calling itself recursively.
332 ///
Chandler Carruth50c909b2011-08-31 23:59:23 +0000333 /// FIXME: Break up massive function into logical units.
334 ///
335 /// \param Loc The location for this caret.
336 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000337 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000338 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000339 /// \param OnMacroInst The current depth of the macro expansion stack.
340 void Emit(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000341 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000342 ArrayRef<FixItHint> Hints,
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000343 unsigned &MacroDepth,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000344 unsigned OnMacroInst = 0) {
345 assert(!Loc.isInvalid() && "must have a valid source location here");
346
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000347 // If this is a file source location, directly emit the source snippet and
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000348 // caret line. Also record the macro depth reached.
349 if (Loc.isFileID()) {
350 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
351 MacroDepth = OnMacroInst;
352 EmitSnippetAndCaret(Loc, Ranges, Hints);
353 return;
354 }
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000355 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000356
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000357 // When processing macros, skip over the expansions leading up to
358 // a macro argument, and trace the argument's expansion stack instead.
359 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000360
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000361 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000362
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000363 // FIXME: Map ranges?
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000364 Emit(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000365
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000366 // Map the location.
367 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000368
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000369 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
370 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
371 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
372 DiagOpts.MacroBacktraceLimit % 2;
373 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
374 }
375
376 // Whether to suppress printing this macro expansion.
377 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
378 OnMacroInst < MacroSkipEnd);
379
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000380 // Map the ranges.
381 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
382 E = Ranges.end();
383 I != E; ++I) {
384 SourceLocation Start = I->getBegin(), End = I->getEnd();
385 if (Start.isMacroID())
386 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
387 if (End.isMacroID())
388 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
389 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000390
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000391 if (!Suppressed) {
392 // Don't print recursive expansion notes from an expansion note.
393 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000394
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000395 // Get the pretty name, according to #line directives etc.
396 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
397 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000398 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000399
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000400 // If this diagnostic is not in the main file, print out the
401 // "included from" lines.
402 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000403
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000404 if (DiagOpts.ShowLocation) {
405 // Emit the file/line/column that this expansion came from.
406 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
407 if (DiagOpts.ShowColumn)
408 OS << PLoc.getColumn() << ':';
409 OS << ' ';
410 }
411 OS << "note: expanded from:\n";
412
413 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000414 return;
415 }
416
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000417 if (OnMacroInst == MacroSkipStart) {
418 // Tell the user that we've skipped contexts.
419 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
420 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
421 "all)\n";
422 }
423 }
424
425 /// \brief Emit a code snippet and caret line.
426 ///
427 /// This routine emits a single line's code snippet and caret line..
428 ///
429 /// \param Loc The location for the caret.
430 /// \param Ranges The underlined ranges for this code snippet.
431 /// \param Hints The FixIt hints active for this diagnostic.
432 void EmitSnippetAndCaret(SourceLocation Loc,
433 SmallVectorImpl<CharSourceRange>& Ranges,
434 ArrayRef<FixItHint> Hints) {
435 assert(!Loc.isInvalid() && "must have a valid source location here");
436 assert(Loc.isFileID() && "must have a file location here");
437
Chandler Carruth50c909b2011-08-31 23:59:23 +0000438 // Decompose the location into a FID/Offset pair.
439 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
440 FileID FID = LocInfo.first;
441 unsigned FileOffset = LocInfo.second;
442
443 // Get information about the buffer it points into.
444 bool Invalid = false;
445 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
446 if (Invalid)
447 return;
448
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000449 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000450 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
451 unsigned CaretEndColNo
452 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
453
454 // Rewind from the current position to the start of the line.
455 const char *TokPtr = BufStart+FileOffset;
456 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
457
458
459 // Compute the line end. Scan forward from the error position to the end of
460 // the line.
461 const char *LineEnd = TokPtr;
462 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
463 ++LineEnd;
464
465 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
466 // the source line length as currently being computed. See
467 // test/Misc/message-length.c.
468 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
469
470 // Copy the line of code into an std::string for ease of manipulation.
471 std::string SourceLine(LineStart, LineEnd);
472
473 // Create a line for the caret that is filled with spaces that is the same
474 // length as the line of source code.
475 std::string CaretLine(LineEnd-LineStart, ' ');
476
477 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000478 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
479 E = Ranges.end();
480 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000481 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000482
483 // Next, insert the caret itself.
484 if (ColNo-1 < CaretLine.size())
485 CaretLine[ColNo-1] = '^';
486 else
487 CaretLine.push_back('^');
488
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000489 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000490
491 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
492 // to produce easily machine parsable output. Add a space before the
493 // source line and the caret to make it trivial to tell the main diagnostic
494 // line from what the user is intended to see.
495 if (DiagOpts.ShowSourceRanges) {
496 SourceLine = ' ' + SourceLine;
497 CaretLine = ' ' + CaretLine;
498 }
499
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000500 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000501 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000502 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000503
504 // If the source line is too long for our terminal, select only the
505 // "interesting" source region within that line.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000506 unsigned Columns = DiagOpts.MessageLength;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000507 if (Columns && SourceLine.size() > Columns)
508 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
509 CaretEndColNo, Columns);
510
511 // Finally, remove any blank spaces from the end of CaretLine.
512 while (CaretLine[CaretLine.size()-1] == ' ')
513 CaretLine.erase(CaretLine.end()-1);
514
515 // Emit what we have computed.
516 OS << SourceLine << '\n';
517
518 if (DiagOpts.ShowColors)
519 OS.changeColor(caretColor, true);
520 OS << CaretLine << '\n';
521 if (DiagOpts.ShowColors)
522 OS.resetColor();
523
524 if (!FixItInsertionLine.empty()) {
525 if (DiagOpts.ShowColors)
526 // Print fixit line in color
527 OS.changeColor(fixitColor, false);
528 if (DiagOpts.ShowSourceRanges)
529 OS << ' ';
530 OS << FixItInsertionLine << '\n';
531 if (DiagOpts.ShowColors)
532 OS.resetColor();
533 }
534
Chandler Carruthcca61582011-09-02 06:30:30 +0000535 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000536 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000537 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000538
Chandler Carruthcca61582011-09-02 06:30:30 +0000539private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000540 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
541 void HighlightRange(const CharSourceRange &R,
542 unsigned LineNo, FileID FID,
543 const std::string &SourceLine,
544 std::string &CaretLine) {
545 assert(CaretLine.size() == SourceLine.size() &&
546 "Expect a correspondence between source and caret line!");
547 if (!R.isValid()) return;
548
549 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
550 SourceLocation End = SM.getExpansionLoc(R.getEnd());
551
552 // If the End location and the start location are the same and are a macro
553 // location, then the range was something that came from a macro expansion
554 // or _Pragma. If this is an object-like macro, the best we can do is to
555 // highlight the range. If this is a function-like macro, we'd also like to
556 // highlight the arguments.
557 if (Begin == End && R.getEnd().isMacroID())
558 End = SM.getExpansionRange(R.getEnd()).second;
559
560 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
561 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
562 return; // No intersection.
563
564 unsigned EndLineNo = SM.getExpansionLineNumber(End);
565 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
566 return; // No intersection.
567
568 // Compute the column number of the start.
569 unsigned StartColNo = 0;
570 if (StartLineNo == LineNo) {
571 StartColNo = SM.getExpansionColumnNumber(Begin);
572 if (StartColNo) --StartColNo; // Zero base the col #.
573 }
574
575 // Compute the column number of the end.
576 unsigned EndColNo = CaretLine.size();
577 if (EndLineNo == LineNo) {
578 EndColNo = SM.getExpansionColumnNumber(End);
579 if (EndColNo) {
580 --EndColNo; // Zero base the col #.
581
582 // Add in the length of the token, so that we cover multi-char tokens if
583 // this is a token range.
584 if (R.isTokenRange())
585 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
586 } else {
587 EndColNo = CaretLine.size();
588 }
589 }
590
591 assert(StartColNo <= EndColNo && "Invalid range!");
592
593 // Check that a token range does not highlight only whitespace.
594 if (R.isTokenRange()) {
595 // Pick the first non-whitespace column.
596 while (StartColNo < SourceLine.size() &&
597 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
598 ++StartColNo;
599
600 // Pick the last non-whitespace column.
601 if (EndColNo > SourceLine.size())
602 EndColNo = SourceLine.size();
603 while (EndColNo-1 &&
604 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
605 --EndColNo;
606
607 // If the start/end passed each other, then we are trying to highlight a
608 // range that just exists in whitespace, which must be some sort of other
609 // bug.
610 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
611 }
612
613 // Fill the range with ~'s.
614 for (unsigned i = StartColNo; i < EndColNo; ++i)
615 CaretLine[i] = '~';
616 }
617
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000618 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000619 const char *LineStart,
620 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000621 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000622 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000623 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000624 return FixItInsertionLine;
625
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000626 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
627 I != E; ++I) {
628 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000629 // We have an insertion hint. Determine whether the inserted
630 // code is on the same line as the caret.
631 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000632 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000633 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000634 // Insert the new code into the line just below the code
635 // that the user wrote.
636 unsigned HintColNo
637 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
638 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000639 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000640 if (LastColumnModified > FixItInsertionLine.size())
641 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000642 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000643 FixItInsertionLine.begin() + HintColNo - 1);
644 } else {
645 FixItInsertionLine.clear();
646 break;
647 }
648 }
649 }
650
651 if (FixItInsertionLine.empty())
652 return FixItInsertionLine;
653
654 // Now that we have the entire fixit line, expand the tabs in it.
655 // Since we don't want to insert spaces in the middle of a word,
656 // find each word and the column it should line up with and insert
657 // spaces until they match.
658 unsigned FixItPos = 0;
659 unsigned LinePos = 0;
660 unsigned TabExpandedCol = 0;
661 unsigned LineLength = LineEnd - LineStart;
662
663 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
664 // Find the next word in the FixIt line.
665 while (FixItPos < FixItInsertionLine.size() &&
666 FixItInsertionLine[FixItPos] == ' ')
667 ++FixItPos;
668 unsigned CharDistance = FixItPos - TabExpandedCol;
669
670 // Walk forward in the source line, keeping track of
671 // the tab-expanded column.
672 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
673 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
674 ++TabExpandedCol;
675 else
676 TabExpandedCol =
677 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
678
679 // Adjust the fixit line to match this column.
680 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
681 FixItPos = TabExpandedCol;
682
683 // Walk to the end of the word.
684 while (FixItPos < FixItInsertionLine.size() &&
685 FixItInsertionLine[FixItPos] != ' ')
686 ++FixItPos;
687 }
688
689 return FixItInsertionLine;
690 }
691
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000692 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
693 // Scan the source line, looking for tabs. If we find any, manually expand
694 // them to spaces and update the CaretLine to match.
695 for (unsigned i = 0; i != SourceLine.size(); ++i) {
696 if (SourceLine[i] != '\t') continue;
697
698 // Replace this tab with at least one space.
699 SourceLine[i] = ' ';
700
701 // Compute the number of spaces we need to insert.
702 unsigned TabStop = DiagOpts.TabStop;
703 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
704 "Invalid -ftabstop value");
705 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
706 assert(NumSpaces < TabStop && "Invalid computation of space amt");
707
708 // Insert spaces into the SourceLine.
709 SourceLine.insert(i+1, NumSpaces, ' ');
710
711 // Insert spaces or ~'s into CaretLine.
712 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
713 }
714 }
715
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000716 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000717 if (!DiagOpts.ShowParseableFixits)
718 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000719
Chandler Carruthcca61582011-09-02 06:30:30 +0000720 // We follow FixItRewriter's example in not (yet) handling
721 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000722 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
723 I != E; ++I) {
724 if (I->RemoveRange.isInvalid() ||
725 I->RemoveRange.getBegin().isMacroID() ||
726 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000727 return;
728 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000729
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000730 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
731 I != E; ++I) {
732 SourceLocation BLoc = I->RemoveRange.getBegin();
733 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000734
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000735 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
736 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000737
Chandler Carruthcca61582011-09-02 06:30:30 +0000738 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000739 if (I->RemoveRange.isTokenRange())
740 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000741
Chandler Carruthcca61582011-09-02 06:30:30 +0000742 // We specifically do not do word-wrapping or tab-expansion here,
743 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000744 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000745 if (PLoc.isInvalid())
746 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000747
Chandler Carruthcca61582011-09-02 06:30:30 +0000748 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000749 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000750 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
751 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
752 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
753 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
754 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000755 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000756 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000757 }
758 }
759};
760
761} // end namespace
762
Chandler Carruth5182a182011-09-07 01:47:09 +0000763void TextDiagnosticPrinter::EmitCaretDiagnostic(
764 SourceLocation Loc,
765 SmallVectorImpl<CharSourceRange>& Ranges,
766 const SourceManager &SM,
Chandler Carruth8be5c152011-09-25 22:31:58 +0000767 ArrayRef<FixItHint> Hints) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000768 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chandler Carruth50c909b2011-08-31 23:59:23 +0000769 assert(DiagOpts && "Unexpected diagnostic without options set");
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000770
Chandler Carruth50c909b2011-08-31 23:59:23 +0000771 // FIXME: Remove this method and have clients directly build and call Emit on
772 // the CaretDiagnostic object.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000773 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts);
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000774 unsigned MacroDepth = 0;
775 CaretDiag.Emit(Loc, Ranges, Hints, MacroDepth);
Chris Lattner94f55782009-02-17 07:38:37 +0000776}
777
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000778/// \brief Skip over whitespace in the string, starting at the given
779/// index.
780///
781/// \returns The index of the first non-whitespace character that is
782/// greater than or equal to Idx or, if no such character exists,
783/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000784static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000785 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000786 unsigned Length) {
787 while (Idx < Length && isspace(Str[Idx]))
788 ++Idx;
789 return Idx;
790}
791
792/// \brief If the given character is the start of some kind of
793/// balanced punctuation (e.g., quotes or parentheses), return the
794/// character that will terminate the punctuation.
795///
796/// \returns The ending punctuation character, if any, or the NULL
797/// character if the input character does not start any punctuation.
798static inline char findMatchingPunctuation(char c) {
799 switch (c) {
800 case '\'': return '\'';
801 case '`': return '\'';
802 case '"': return '"';
803 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000804 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000805 case '{': return '}';
806 default: break;
807 }
808
809 return 0;
810}
811
812/// \brief Find the end of the word starting at the given offset
813/// within a string.
814///
815/// \returns the index pointing one character past the end of the
816/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000817static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000818 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000819 unsigned Length, unsigned Column,
820 unsigned Columns) {
821 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000822 unsigned End = Start + 1;
823
Daniel Dunbareae18f82009-12-06 09:56:18 +0000824 // If we are already at the end of the string, take that as the word.
825 if (End == Str.size())
826 return End;
827
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000828 // Determine if the start of the string is actually opening
829 // punctuation, e.g., a quote or parentheses.
830 char EndPunct = findMatchingPunctuation(Str[Start]);
831 if (!EndPunct) {
832 // This is a normal word. Just find the first space character.
833 while (End < Length && !isspace(Str[End]))
834 ++End;
835 return End;
836 }
837
838 // We have the start of a balanced punctuation sequence (quotes,
839 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000840 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000841 PunctuationEndStack.push_back(EndPunct);
842 while (End < Length && !PunctuationEndStack.empty()) {
843 if (Str[End] == PunctuationEndStack.back())
844 PunctuationEndStack.pop_back();
845 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
846 PunctuationEndStack.push_back(SubEndPunct);
847
848 ++End;
849 }
850
851 // Find the first space character after the punctuation ended.
852 while (End < Length && !isspace(Str[End]))
853 ++End;
854
855 unsigned PunctWordLength = End - Start;
856 if (// If the word fits on this line
857 Column + PunctWordLength <= Columns ||
858 // ... or the word is "short enough" to take up the next line
859 // without too much ugly white space
860 PunctWordLength < Columns/3)
861 return End; // Take the whole thing as a single "word".
862
863 // The whole quoted/parenthesized string is too long to print as a
864 // single "word". Instead, find the "word" that starts just after
865 // the punctuation and use that end-point instead. This will recurse
866 // until it finds something small enough to consider a word.
867 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
868}
869
870/// \brief Print the given string to a stream, word-wrapping it to
871/// some number of columns in the process.
872///
873/// \brief OS the stream to which the word-wrapping string will be
874/// emitted.
875///
876/// \brief Str the string to word-wrap and output.
877///
878/// \brief Columns the number of columns to word-wrap to.
879///
880/// \brief Column the column number at which the first character of \p
881/// Str will be printed. This will be non-zero when part of the first
882/// line has already been printed.
883///
884/// \brief Indentation the number of spaces to indent any lines beyond
885/// the first line.
886///
887/// \returns true if word-wrapping was required, or false if the
888/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000889static bool PrintWordWrapped(raw_ostream &OS,
890 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000891 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000892 unsigned Column = 0,
893 unsigned Indentation = WordWrapIndentation) {
894 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000895
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000896 // If there is a newline in this message somewhere, find that
897 // newline and split the message into the part before the newline
898 // (which will be word-wrapped) and the part from the newline one
899 // (which will be emitted unchanged).
900 for (unsigned I = 0; I != Length; ++I)
901 if (Str[I] == '\n') {
902 Length = I;
903 break;
904 }
905
906 // The string used to indent each line.
907 llvm::SmallString<16> IndentStr;
908 IndentStr.assign(Indentation, ' ');
909 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000910 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000911 WordStart = WordEnd) {
912 // Find the beginning of the next word.
913 WordStart = skipWhitespace(WordStart, Str, Length);
914 if (WordStart == Length)
915 break;
916
917 // Find the end of this word.
918 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000919
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000920 // Does this word fit on the current line?
921 unsigned WordLength = WordEnd - WordStart;
922 if (Column + WordLength < Columns) {
923 // This word fits on the current line; print it there.
924 if (WordStart) {
925 OS << ' ';
926 Column += 1;
927 }
928 OS.write(&Str[WordStart], WordLength);
929 Column += WordLength;
930 continue;
931 }
932
933 // This word does not fit on the current line, so wrap to the next
934 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000935 OS << '\n';
936 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000937 OS.write(&Str[WordStart], WordLength);
938 Column = Indentation + WordLength;
939 Wrapped = true;
940 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000941
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000942 if (Length == Str.size())
943 return Wrapped; // We're done.
944
945 // There is a newline in the message, followed by something that
946 // will not be word-wrapped. Print that.
947 OS.write(&Str[Length], Str.size() - Length);
948 return true;
949}
Chris Lattner94f55782009-02-17 07:38:37 +0000950
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000951/// Get the presumed location of a diagnostic message. This computes the
952/// presumed location for the top of any macro backtrace when present.
953static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
954 SourceLocation Loc) {
955 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
956 // walk to the top of the macro call stack.
957 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000958 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000959 Loc = getImmediateMacroCallerLoc(SM, Loc);
960 }
961
962 return SM.getPresumedLoc(Loc);
963}
964
Chandler Carruth5770bb72011-09-07 08:05:58 +0000965/// \brief Print out the file/line/column information and include trace.
966///
967/// This method handlen the emission of the diagnostic location information.
968/// This includes extracting as much location information as is present for the
969/// diagnostic and printing it, as well as any include stack or source ranges
970/// necessary.
971void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
972 const DiagnosticInfo &Info,
973 const SourceManager &SM,
974 PresumedLoc PLoc) {
975 if (PLoc.isInvalid()) {
976 // At least print the file name if available:
977 FileID FID = SM.getFileID(Info.getLocation());
978 if (!FID.isInvalid()) {
979 const FileEntry* FE = SM.getFileEntryForID(FID);
980 if (FE && FE->getName()) {
981 OS << FE->getName();
982 if (FE->getDevice() == 0 && FE->getInode() == 0
983 && FE->getFileMode() == 0) {
984 // in PCH is a guess, but a good one:
985 OS << " (in PCH)";
986 }
987 OS << ": ";
988 }
989 }
990 return;
991 }
992 unsigned LineNo = PLoc.getLine();
993
994 if (!DiagOpts->ShowLocation)
995 return;
996
997 if (DiagOpts->ShowColors)
998 OS.changeColor(savedColor, true);
999
1000 OS << PLoc.getFilename();
1001 switch (DiagOpts->Format) {
1002 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
1003 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
1004 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
1005 }
1006
1007 if (DiagOpts->ShowColumn)
1008 // Compute the column number.
1009 if (unsigned ColNo = PLoc.getColumn()) {
1010 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
1011 OS << ',';
1012 ColNo--;
1013 } else
1014 OS << ':';
1015 OS << ColNo;
1016 }
1017 switch (DiagOpts->Format) {
1018 case DiagnosticOptions::Clang:
1019 case DiagnosticOptions::Vi: OS << ':'; break;
1020 case DiagnosticOptions::Msvc: OS << ") : "; break;
1021 }
1022
1023 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1024 FileID CaretFileID =
1025 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1026 bool PrintedRange = false;
1027
1028 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1029 // Ignore invalid ranges.
1030 if (!Info.getRange(i).isValid()) continue;
1031
1032 SourceLocation B = Info.getRange(i).getBegin();
1033 SourceLocation E = Info.getRange(i).getEnd();
1034 B = SM.getExpansionLoc(B);
1035 E = SM.getExpansionLoc(E);
1036
1037 // If the End location and the start location are the same and are a
1038 // macro location, then the range was something that came from a
1039 // macro expansion or _Pragma. If this is an object-like macro, the
1040 // best we can do is to highlight the range. If this is a
1041 // function-like macro, we'd also like to highlight the arguments.
1042 if (B == E && Info.getRange(i).getEnd().isMacroID())
1043 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1044
1045 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1046 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1047
1048 // If the start or end of the range is in another file, just discard
1049 // it.
1050 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1051 continue;
1052
1053 // Add in the length of the token, so that we cover multi-char
1054 // tokens.
1055 unsigned TokSize = 0;
1056 if (Info.getRange(i).isTokenRange())
1057 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1058
1059 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1060 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1061 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1062 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1063 << '}';
1064 PrintedRange = true;
1065 }
1066
1067 if (PrintedRange)
1068 OS << ':';
1069 }
1070 OS << ' ';
1071}
1072
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001073void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +00001074 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +00001075 // Default implementation (Warnings/errors count).
1076 DiagnosticClient::HandleDiagnostic(Level, Info);
1077
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001078 // Keeps track of the the starting position of the location
1079 // information (e.g., "foo.c:10:4:") that precedes the error
1080 // message. We use this information to determine how long the
1081 // file+line+column number prefix is.
1082 uint64_t StartOfLocationInfo = OS.tell();
1083
Daniel Dunbarb96b6702010-02-25 03:23:40 +00001084 if (!Prefix.empty())
1085 OS << Prefix << ": ";
1086
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001087 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001088 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001089 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001090
Chandler Carruth5770bb72011-09-07 08:05:58 +00001091 // First, if this diagnostic is not in the main file, print out the
1092 // "included from" lines.
1093 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1094 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +00001095
Chandler Carruth5770bb72011-09-07 08:05:58 +00001096 // Next emit the location of this particular diagnostic.
1097 EmitDiagnosticLoc(Level, Info, SM, PLoc);
Axel Naumann04331162011-01-27 10:55:51 +00001098
Chandler Carruth5770bb72011-09-07 08:05:58 +00001099 if (DiagOpts->ShowColors)
1100 OS.resetColor();
Torok Edwin603fca72009-06-04 07:18:23 +00001101 }
1102
Daniel Dunbareace8742009-11-04 06:24:30 +00001103 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001104 // Print diagnostic category in bold and color
1105 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001106 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Torok Edwin603fca72009-06-04 07:18:23 +00001107 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1108 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1109 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1110 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001111 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001113
Reid Spencer5f016e22007-07-11 17:01:13 +00001114 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001115 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001116 case Diagnostic::Note: OS << "note: "; break;
1117 case Diagnostic::Warning: OS << "warning: "; break;
1118 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001119 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001120 }
Torok Edwin603fca72009-06-04 07:18:23 +00001121
Daniel Dunbareace8742009-11-04 06:24:30 +00001122 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001123 OS.resetColor();
1124
Chris Lattnerf4c83962008-11-19 06:51:40 +00001125 llvm::SmallString<100> OutStr;
1126 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001127
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001128 if (DiagOpts->ShowNames &&
1129 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1130 OutStr += " [";
1131 OutStr += DiagnosticIDs::getName(Info.getID());
1132 OutStr += "]";
1133 }
1134
Chris Lattnerc9b88902010-05-04 21:13:21 +00001135 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001136 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001137 // Was this a warning mapped to an error using -Werror or pragma?
1138 if (Level == Diagnostic::Error &&
1139 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1140 diag::Mapping mapping = diag::MAP_IGNORE;
1141 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1142 &mapping);
1143 if (mapping == diag::MAP_WARNING)
1144 OptionName += "-Werror";
1145 }
1146
Chris Lattner5f9e2722011-07-23 10:55:15 +00001147 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001148 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001149 if (!OptionName.empty())
1150 OptionName += ',';
1151 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001152 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001153 } else if (Info.getID() == diag::fatal_too_many_errors) {
1154 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001155 } else {
1156 // If the diagnostic is an extension diagnostic and not enabled by default
1157 // then it must have been turned on with -pedantic.
1158 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001159 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1160 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001161 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001162 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001163 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001164 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001165
1166 // If the user wants to see category information, include it too.
1167 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001168 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001169 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001170
Chris Lattnerc9b88902010-05-04 21:13:21 +00001171 // If there is any categorization information, include it.
1172 if (!OptionName.empty() || DiagCategory != 0) {
1173 bool NeedsComma = false;
1174 OutStr += " [";
1175
1176 if (!OptionName.empty()) {
1177 OutStr += OptionName;
1178 NeedsComma = true;
1179 }
1180
1181 if (DiagCategory) {
1182 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001183 if (DiagOpts->ShowCategories == 1)
1184 OutStr += llvm::utostr(DiagCategory);
1185 else {
1186 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001187 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001188 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001189 }
1190
1191 OutStr += "]";
1192 }
1193
1194
Daniel Dunbareace8742009-11-04 06:24:30 +00001195 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001196 // Print warnings, errors and fatal errors in bold, no color
1197 switch (Level) {
1198 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1199 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1200 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1201 default: break; //don't bold notes
1202 }
1203 }
1204
Daniel Dunbareace8742009-11-04 06:24:30 +00001205 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001206 // We will be word-wrapping the error message, so compute the
1207 // column number where we currently are (after printing the
1208 // location information).
1209 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001210 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001211 } else {
1212 OS.write(OutStr.begin(), OutStr.size());
1213 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001214 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001215 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001216 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001217
Douglas Gregordf667e72009-03-10 20:44:00 +00001218 // If caret diagnostics are enabled and we have location, we want to
1219 // emit the caret. However, we only do this if the location moved
1220 // from the last diagnostic, if the last diagnostic was a note that
1221 // was part of a different warning or error diagnostic, or if the
1222 // diagnostic has ranges. We don't want to emit the same caret
1223 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001224 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001225 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001226 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001227 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001228 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001229 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001230 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001231
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001232 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001233 SmallVector<CharSourceRange, 20> Ranges;
1234 Ranges.reserve(Info.getNumRanges());
1235 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1236 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001237
Chandler Carruth5182a182011-09-07 01:47:09 +00001238 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001239 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001240 if (Hint.RemoveRange.isValid())
1241 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001242 }
1243
Chandler Carruth5182a182011-09-07 01:47:09 +00001244 EmitCaretDiagnostic(LastLoc, Ranges, LastLoc.getManager(),
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001245 llvm::makeArrayRef(Info.getFixItHints(),
Chandler Carruth8be5c152011-09-25 22:31:58 +00001246 Info.getNumFixItHints()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001248
Chris Lattnera03a5b52008-11-19 06:56:25 +00001249 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001250}