blob: 17e63b9ab95046b00f3830af61bcd8ad8ce563b8 [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
351 // If this is a macro ID, first emit information about where this was
352 // expanded (recursively) then emit information about where the token was
353 // spelled from.
354 if (!Loc.isFileID()) {
355 // Whether to suppress printing this macro expansion.
356 bool Suppressed
357 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
358
359 // When processing macros, skip over the expansions leading up to
360 // a macro argument, and trace the argument's expansion stack instead.
361 Loc = skipToMacroArgExpansion(SM, Loc);
362
363 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
364
365 // FIXME: Map ranges?
Chandler Carruth5182a182011-09-07 01:47:09 +0000366 Emit(OneLevelUp, Ranges, Hints, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000367
368 // Map the location.
369 Loc = getImmediateMacroCalleeLoc(SM, Loc);
370
371 // Map the ranges.
Chandler Carruth5182a182011-09-07 01:47:09 +0000372 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
373 E = Ranges.end();
374 I != E; ++I) {
375 SourceLocation Start = I->getBegin(), End = I->getEnd();
376 if (Start.isMacroID())
377 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
378 if (End.isMacroID())
379 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
Chandler Carruth50c909b2011-08-31 23:59:23 +0000380 }
381
382 if (!Suppressed) {
383 // Don't print recursive expansion notes from an expansion note.
384 Loc = SM.getSpellingLoc(Loc);
385
386 // Get the pretty name, according to #line directives etc.
387 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
388 if (PLoc.isInvalid())
389 return;
390
391 // If this diagnostic is not in the main file, print out the
392 // "included from" lines.
393 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
394
395 if (DiagOpts.ShowLocation) {
396 // Emit the file/line/column that this expansion came from.
397 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
398 if (DiagOpts.ShowColumn)
399 OS << PLoc.getColumn() << ':';
400 OS << ' ';
401 }
402 OS << "note: expanded from:\n";
403
Chandler Carruth5182a182011-09-07 01:47:09 +0000404 Emit(Loc, Ranges, ArrayRef<FixItHint>(), OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000405 return;
406 }
407
408 if (OnMacroInst == MacroSkipStart) {
409 // Tell the user that we've skipped contexts.
410 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
411 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
412 "all)\n";
413 }
414
415 return;
416 }
417
418 // Decompose the location into a FID/Offset pair.
419 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
420 FileID FID = LocInfo.first;
421 unsigned FileOffset = LocInfo.second;
422
423 // Get information about the buffer it points into.
424 bool Invalid = false;
425 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
426 if (Invalid)
427 return;
428
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000429 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000430 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
431 unsigned CaretEndColNo
432 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
433
434 // Rewind from the current position to the start of the line.
435 const char *TokPtr = BufStart+FileOffset;
436 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
437
438
439 // Compute the line end. Scan forward from the error position to the end of
440 // the line.
441 const char *LineEnd = TokPtr;
442 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
443 ++LineEnd;
444
445 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
446 // the source line length as currently being computed. See
447 // test/Misc/message-length.c.
448 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
449
450 // Copy the line of code into an std::string for ease of manipulation.
451 std::string SourceLine(LineStart, LineEnd);
452
453 // Create a line for the caret that is filled with spaces that is the same
454 // length as the line of source code.
455 std::string CaretLine(LineEnd-LineStart, ' ');
456
457 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000458 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
459 E = Ranges.end();
460 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000461 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000462
463 // Next, insert the caret itself.
464 if (ColNo-1 < CaretLine.size())
465 CaretLine[ColNo-1] = '^';
466 else
467 CaretLine.push_back('^');
468
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000469 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000470
471 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
472 // to produce easily machine parsable output. Add a space before the
473 // source line and the caret to make it trivial to tell the main diagnostic
474 // line from what the user is intended to see.
475 if (DiagOpts.ShowSourceRanges) {
476 SourceLine = ' ' + SourceLine;
477 CaretLine = ' ' + CaretLine;
478 }
479
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000480 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000481 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000482 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000483
484 // If the source line is too long for our terminal, select only the
485 // "interesting" source region within that line.
486 if (Columns && SourceLine.size() > Columns)
487 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
488 CaretEndColNo, Columns);
489
490 // Finally, remove any blank spaces from the end of CaretLine.
491 while (CaretLine[CaretLine.size()-1] == ' ')
492 CaretLine.erase(CaretLine.end()-1);
493
494 // Emit what we have computed.
495 OS << SourceLine << '\n';
496
497 if (DiagOpts.ShowColors)
498 OS.changeColor(caretColor, true);
499 OS << CaretLine << '\n';
500 if (DiagOpts.ShowColors)
501 OS.resetColor();
502
503 if (!FixItInsertionLine.empty()) {
504 if (DiagOpts.ShowColors)
505 // Print fixit line in color
506 OS.changeColor(fixitColor, false);
507 if (DiagOpts.ShowSourceRanges)
508 OS << ' ';
509 OS << FixItInsertionLine << '\n';
510 if (DiagOpts.ShowColors)
511 OS.resetColor();
512 }
513
Chandler Carruthcca61582011-09-02 06:30:30 +0000514 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000515 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000516 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000517
Chandler Carruthcca61582011-09-02 06:30:30 +0000518private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000519 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
520 void HighlightRange(const CharSourceRange &R,
521 unsigned LineNo, FileID FID,
522 const std::string &SourceLine,
523 std::string &CaretLine) {
524 assert(CaretLine.size() == SourceLine.size() &&
525 "Expect a correspondence between source and caret line!");
526 if (!R.isValid()) return;
527
528 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
529 SourceLocation End = SM.getExpansionLoc(R.getEnd());
530
531 // If the End location and the start location are the same and are a macro
532 // location, then the range was something that came from a macro expansion
533 // or _Pragma. If this is an object-like macro, the best we can do is to
534 // highlight the range. If this is a function-like macro, we'd also like to
535 // highlight the arguments.
536 if (Begin == End && R.getEnd().isMacroID())
537 End = SM.getExpansionRange(R.getEnd()).second;
538
539 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
540 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
541 return; // No intersection.
542
543 unsigned EndLineNo = SM.getExpansionLineNumber(End);
544 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
545 return; // No intersection.
546
547 // Compute the column number of the start.
548 unsigned StartColNo = 0;
549 if (StartLineNo == LineNo) {
550 StartColNo = SM.getExpansionColumnNumber(Begin);
551 if (StartColNo) --StartColNo; // Zero base the col #.
552 }
553
554 // Compute the column number of the end.
555 unsigned EndColNo = CaretLine.size();
556 if (EndLineNo == LineNo) {
557 EndColNo = SM.getExpansionColumnNumber(End);
558 if (EndColNo) {
559 --EndColNo; // Zero base the col #.
560
561 // Add in the length of the token, so that we cover multi-char tokens if
562 // this is a token range.
563 if (R.isTokenRange())
564 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
565 } else {
566 EndColNo = CaretLine.size();
567 }
568 }
569
570 assert(StartColNo <= EndColNo && "Invalid range!");
571
572 // Check that a token range does not highlight only whitespace.
573 if (R.isTokenRange()) {
574 // Pick the first non-whitespace column.
575 while (StartColNo < SourceLine.size() &&
576 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
577 ++StartColNo;
578
579 // Pick the last non-whitespace column.
580 if (EndColNo > SourceLine.size())
581 EndColNo = SourceLine.size();
582 while (EndColNo-1 &&
583 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
584 --EndColNo;
585
586 // If the start/end passed each other, then we are trying to highlight a
587 // range that just exists in whitespace, which must be some sort of other
588 // bug.
589 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
590 }
591
592 // Fill the range with ~'s.
593 for (unsigned i = StartColNo; i < EndColNo; ++i)
594 CaretLine[i] = '~';
595 }
596
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000597 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000598 const char *LineStart,
599 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000600 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000601 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000602 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000603 return FixItInsertionLine;
604
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000605 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
606 I != E; ++I) {
607 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000608 // We have an insertion hint. Determine whether the inserted
609 // code is on the same line as the caret.
610 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000611 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000612 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000613 // Insert the new code into the line just below the code
614 // that the user wrote.
615 unsigned HintColNo
616 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
617 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000618 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000619 if (LastColumnModified > FixItInsertionLine.size())
620 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000621 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000622 FixItInsertionLine.begin() + HintColNo - 1);
623 } else {
624 FixItInsertionLine.clear();
625 break;
626 }
627 }
628 }
629
630 if (FixItInsertionLine.empty())
631 return FixItInsertionLine;
632
633 // Now that we have the entire fixit line, expand the tabs in it.
634 // Since we don't want to insert spaces in the middle of a word,
635 // find each word and the column it should line up with and insert
636 // spaces until they match.
637 unsigned FixItPos = 0;
638 unsigned LinePos = 0;
639 unsigned TabExpandedCol = 0;
640 unsigned LineLength = LineEnd - LineStart;
641
642 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
643 // Find the next word in the FixIt line.
644 while (FixItPos < FixItInsertionLine.size() &&
645 FixItInsertionLine[FixItPos] == ' ')
646 ++FixItPos;
647 unsigned CharDistance = FixItPos - TabExpandedCol;
648
649 // Walk forward in the source line, keeping track of
650 // the tab-expanded column.
651 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
652 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
653 ++TabExpandedCol;
654 else
655 TabExpandedCol =
656 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
657
658 // Adjust the fixit line to match this column.
659 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
660 FixItPos = TabExpandedCol;
661
662 // Walk to the end of the word.
663 while (FixItPos < FixItInsertionLine.size() &&
664 FixItInsertionLine[FixItPos] != ' ')
665 ++FixItPos;
666 }
667
668 return FixItInsertionLine;
669 }
670
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000671 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
672 // Scan the source line, looking for tabs. If we find any, manually expand
673 // them to spaces and update the CaretLine to match.
674 for (unsigned i = 0; i != SourceLine.size(); ++i) {
675 if (SourceLine[i] != '\t') continue;
676
677 // Replace this tab with at least one space.
678 SourceLine[i] = ' ';
679
680 // Compute the number of spaces we need to insert.
681 unsigned TabStop = DiagOpts.TabStop;
682 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
683 "Invalid -ftabstop value");
684 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
685 assert(NumSpaces < TabStop && "Invalid computation of space amt");
686
687 // Insert spaces into the SourceLine.
688 SourceLine.insert(i+1, NumSpaces, ' ');
689
690 // Insert spaces or ~'s into CaretLine.
691 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
692 }
693 }
694
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000695 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000696 if (!DiagOpts.ShowParseableFixits)
697 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000698
Chandler Carruthcca61582011-09-02 06:30:30 +0000699 // We follow FixItRewriter's example in not (yet) handling
700 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000701 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
702 I != E; ++I) {
703 if (I->RemoveRange.isInvalid() ||
704 I->RemoveRange.getBegin().isMacroID() ||
705 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000706 return;
707 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000708
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000709 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
710 I != E; ++I) {
711 SourceLocation BLoc = I->RemoveRange.getBegin();
712 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000713
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000714 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
715 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000716
Chandler Carruthcca61582011-09-02 06:30:30 +0000717 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000718 if (I->RemoveRange.isTokenRange())
719 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000720
Chandler Carruthcca61582011-09-02 06:30:30 +0000721 // We specifically do not do word-wrapping or tab-expansion here,
722 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000723 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000724 if (PLoc.isInvalid())
725 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000726
Chandler Carruthcca61582011-09-02 06:30:30 +0000727 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000728 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000729 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
730 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
731 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
732 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
733 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000734 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000735 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000736 }
737 }
738};
739
740} // end namespace
741
Chandler Carruth5182a182011-09-07 01:47:09 +0000742void TextDiagnosticPrinter::EmitCaretDiagnostic(
743 SourceLocation Loc,
744 SmallVectorImpl<CharSourceRange>& Ranges,
745 const SourceManager &SM,
746 ArrayRef<FixItHint> Hints,
747 unsigned Columns,
748 unsigned MacroSkipStart,
749 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000750 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chandler Carruth50c909b2011-08-31 23:59:23 +0000751 assert(DiagOpts && "Unexpected diagnostic without options set");
752 // FIXME: Remove this method and have clients directly build and call Emit on
753 // the CaretDiagnostic object.
754 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts,
755 Columns, MacroSkipStart, MacroSkipEnd);
Chandler Carruth5182a182011-09-07 01:47:09 +0000756 CaretDiag.Emit(Loc, Ranges, Hints);
Chris Lattner94f55782009-02-17 07:38:37 +0000757}
758
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000759/// \brief Skip over whitespace in the string, starting at the given
760/// index.
761///
762/// \returns The index of the first non-whitespace character that is
763/// greater than or equal to Idx or, if no such character exists,
764/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000765static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000766 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000767 unsigned Length) {
768 while (Idx < Length && isspace(Str[Idx]))
769 ++Idx;
770 return Idx;
771}
772
773/// \brief If the given character is the start of some kind of
774/// balanced punctuation (e.g., quotes or parentheses), return the
775/// character that will terminate the punctuation.
776///
777/// \returns The ending punctuation character, if any, or the NULL
778/// character if the input character does not start any punctuation.
779static inline char findMatchingPunctuation(char c) {
780 switch (c) {
781 case '\'': return '\'';
782 case '`': return '\'';
783 case '"': return '"';
784 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000785 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000786 case '{': return '}';
787 default: break;
788 }
789
790 return 0;
791}
792
793/// \brief Find the end of the word starting at the given offset
794/// within a string.
795///
796/// \returns the index pointing one character past the end of the
797/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000798static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000799 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000800 unsigned Length, unsigned Column,
801 unsigned Columns) {
802 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000803 unsigned End = Start + 1;
804
Daniel Dunbareae18f82009-12-06 09:56:18 +0000805 // If we are already at the end of the string, take that as the word.
806 if (End == Str.size())
807 return End;
808
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000809 // Determine if the start of the string is actually opening
810 // punctuation, e.g., a quote or parentheses.
811 char EndPunct = findMatchingPunctuation(Str[Start]);
812 if (!EndPunct) {
813 // This is a normal word. Just find the first space character.
814 while (End < Length && !isspace(Str[End]))
815 ++End;
816 return End;
817 }
818
819 // We have the start of a balanced punctuation sequence (quotes,
820 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000821 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000822 PunctuationEndStack.push_back(EndPunct);
823 while (End < Length && !PunctuationEndStack.empty()) {
824 if (Str[End] == PunctuationEndStack.back())
825 PunctuationEndStack.pop_back();
826 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
827 PunctuationEndStack.push_back(SubEndPunct);
828
829 ++End;
830 }
831
832 // Find the first space character after the punctuation ended.
833 while (End < Length && !isspace(Str[End]))
834 ++End;
835
836 unsigned PunctWordLength = End - Start;
837 if (// If the word fits on this line
838 Column + PunctWordLength <= Columns ||
839 // ... or the word is "short enough" to take up the next line
840 // without too much ugly white space
841 PunctWordLength < Columns/3)
842 return End; // Take the whole thing as a single "word".
843
844 // The whole quoted/parenthesized string is too long to print as a
845 // single "word". Instead, find the "word" that starts just after
846 // the punctuation and use that end-point instead. This will recurse
847 // until it finds something small enough to consider a word.
848 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
849}
850
851/// \brief Print the given string to a stream, word-wrapping it to
852/// some number of columns in the process.
853///
854/// \brief OS the stream to which the word-wrapping string will be
855/// emitted.
856///
857/// \brief Str the string to word-wrap and output.
858///
859/// \brief Columns the number of columns to word-wrap to.
860///
861/// \brief Column the column number at which the first character of \p
862/// Str will be printed. This will be non-zero when part of the first
863/// line has already been printed.
864///
865/// \brief Indentation the number of spaces to indent any lines beyond
866/// the first line.
867///
868/// \returns true if word-wrapping was required, or false if the
869/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000870static bool PrintWordWrapped(raw_ostream &OS,
871 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000872 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000873 unsigned Column = 0,
874 unsigned Indentation = WordWrapIndentation) {
875 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000876
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000877 // If there is a newline in this message somewhere, find that
878 // newline and split the message into the part before the newline
879 // (which will be word-wrapped) and the part from the newline one
880 // (which will be emitted unchanged).
881 for (unsigned I = 0; I != Length; ++I)
882 if (Str[I] == '\n') {
883 Length = I;
884 break;
885 }
886
887 // The string used to indent each line.
888 llvm::SmallString<16> IndentStr;
889 IndentStr.assign(Indentation, ' ');
890 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000891 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000892 WordStart = WordEnd) {
893 // Find the beginning of the next word.
894 WordStart = skipWhitespace(WordStart, Str, Length);
895 if (WordStart == Length)
896 break;
897
898 // Find the end of this word.
899 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000900
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000901 // Does this word fit on the current line?
902 unsigned WordLength = WordEnd - WordStart;
903 if (Column + WordLength < Columns) {
904 // This word fits on the current line; print it there.
905 if (WordStart) {
906 OS << ' ';
907 Column += 1;
908 }
909 OS.write(&Str[WordStart], WordLength);
910 Column += WordLength;
911 continue;
912 }
913
914 // This word does not fit on the current line, so wrap to the next
915 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000916 OS << '\n';
917 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000918 OS.write(&Str[WordStart], WordLength);
919 Column = Indentation + WordLength;
920 Wrapped = true;
921 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000922
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000923 if (Length == Str.size())
924 return Wrapped; // We're done.
925
926 // There is a newline in the message, followed by something that
927 // will not be word-wrapped. Print that.
928 OS.write(&Str[Length], Str.size() - Length);
929 return true;
930}
Chris Lattner94f55782009-02-17 07:38:37 +0000931
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000932/// Get the presumed location of a diagnostic message. This computes the
933/// presumed location for the top of any macro backtrace when present.
934static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
935 SourceLocation Loc) {
936 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
937 // walk to the top of the macro call stack.
938 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000939 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000940 Loc = getImmediateMacroCallerLoc(SM, Loc);
941 }
942
943 return SM.getPresumedLoc(Loc);
944}
945
Chandler Carruth5770bb72011-09-07 08:05:58 +0000946/// \brief Print out the file/line/column information and include trace.
947///
948/// This method handlen the emission of the diagnostic location information.
949/// This includes extracting as much location information as is present for the
950/// diagnostic and printing it, as well as any include stack or source ranges
951/// necessary.
952void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
953 const DiagnosticInfo &Info,
954 const SourceManager &SM,
955 PresumedLoc PLoc) {
956 if (PLoc.isInvalid()) {
957 // At least print the file name if available:
958 FileID FID = SM.getFileID(Info.getLocation());
959 if (!FID.isInvalid()) {
960 const FileEntry* FE = SM.getFileEntryForID(FID);
961 if (FE && FE->getName()) {
962 OS << FE->getName();
963 if (FE->getDevice() == 0 && FE->getInode() == 0
964 && FE->getFileMode() == 0) {
965 // in PCH is a guess, but a good one:
966 OS << " (in PCH)";
967 }
968 OS << ": ";
969 }
970 }
971 return;
972 }
973 unsigned LineNo = PLoc.getLine();
974
975 if (!DiagOpts->ShowLocation)
976 return;
977
978 if (DiagOpts->ShowColors)
979 OS.changeColor(savedColor, true);
980
981 OS << PLoc.getFilename();
982 switch (DiagOpts->Format) {
983 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
984 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
985 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
986 }
987
988 if (DiagOpts->ShowColumn)
989 // Compute the column number.
990 if (unsigned ColNo = PLoc.getColumn()) {
991 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
992 OS << ',';
993 ColNo--;
994 } else
995 OS << ':';
996 OS << ColNo;
997 }
998 switch (DiagOpts->Format) {
999 case DiagnosticOptions::Clang:
1000 case DiagnosticOptions::Vi: OS << ':'; break;
1001 case DiagnosticOptions::Msvc: OS << ") : "; break;
1002 }
1003
1004 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1005 FileID CaretFileID =
1006 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1007 bool PrintedRange = false;
1008
1009 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1010 // Ignore invalid ranges.
1011 if (!Info.getRange(i).isValid()) continue;
1012
1013 SourceLocation B = Info.getRange(i).getBegin();
1014 SourceLocation E = Info.getRange(i).getEnd();
1015 B = SM.getExpansionLoc(B);
1016 E = SM.getExpansionLoc(E);
1017
1018 // If the End location and the start location are the same and are a
1019 // macro location, then the range was something that came from a
1020 // macro expansion or _Pragma. If this is an object-like macro, the
1021 // best we can do is to highlight the range. If this is a
1022 // function-like macro, we'd also like to highlight the arguments.
1023 if (B == E && Info.getRange(i).getEnd().isMacroID())
1024 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1025
1026 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1027 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1028
1029 // If the start or end of the range is in another file, just discard
1030 // it.
1031 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1032 continue;
1033
1034 // Add in the length of the token, so that we cover multi-char
1035 // tokens.
1036 unsigned TokSize = 0;
1037 if (Info.getRange(i).isTokenRange())
1038 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1039
1040 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1041 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1042 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1043 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1044 << '}';
1045 PrintedRange = true;
1046 }
1047
1048 if (PrintedRange)
1049 OS << ':';
1050 }
1051 OS << ' ';
1052}
1053
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001054void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +00001055 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +00001056 // Default implementation (Warnings/errors count).
1057 DiagnosticClient::HandleDiagnostic(Level, Info);
1058
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001059 // Keeps track of the the starting position of the location
1060 // information (e.g., "foo.c:10:4:") that precedes the error
1061 // message. We use this information to determine how long the
1062 // file+line+column number prefix is.
1063 uint64_t StartOfLocationInfo = OS.tell();
1064
Daniel Dunbarb96b6702010-02-25 03:23:40 +00001065 if (!Prefix.empty())
1066 OS << Prefix << ": ";
1067
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001068 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001069 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001070 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001071
Chandler Carruth5770bb72011-09-07 08:05:58 +00001072 // First, if this diagnostic is not in the main file, print out the
1073 // "included from" lines.
1074 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1075 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +00001076
Chandler Carruth5770bb72011-09-07 08:05:58 +00001077 // Next emit the location of this particular diagnostic.
1078 EmitDiagnosticLoc(Level, Info, SM, PLoc);
Axel Naumann04331162011-01-27 10:55:51 +00001079
Chandler Carruth5770bb72011-09-07 08:05:58 +00001080 if (DiagOpts->ShowColors)
1081 OS.resetColor();
Torok Edwin603fca72009-06-04 07:18:23 +00001082 }
1083
Daniel Dunbareace8742009-11-04 06:24:30 +00001084 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001085 // Print diagnostic category in bold and color
1086 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001087 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Torok Edwin603fca72009-06-04 07:18:23 +00001088 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1089 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1090 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1091 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001092 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001094
Reid Spencer5f016e22007-07-11 17:01:13 +00001095 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001096 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001097 case Diagnostic::Note: OS << "note: "; break;
1098 case Diagnostic::Warning: OS << "warning: "; break;
1099 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001100 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001101 }
Torok Edwin603fca72009-06-04 07:18:23 +00001102
Daniel Dunbareace8742009-11-04 06:24:30 +00001103 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001104 OS.resetColor();
1105
Chris Lattnerf4c83962008-11-19 06:51:40 +00001106 llvm::SmallString<100> OutStr;
1107 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001108
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001109 if (DiagOpts->ShowNames &&
1110 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1111 OutStr += " [";
1112 OutStr += DiagnosticIDs::getName(Info.getID());
1113 OutStr += "]";
1114 }
1115
Chris Lattnerc9b88902010-05-04 21:13:21 +00001116 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001117 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001118 // Was this a warning mapped to an error using -Werror or pragma?
1119 if (Level == Diagnostic::Error &&
1120 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1121 diag::Mapping mapping = diag::MAP_IGNORE;
1122 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1123 &mapping);
1124 if (mapping == diag::MAP_WARNING)
1125 OptionName += "-Werror";
1126 }
1127
Chris Lattner5f9e2722011-07-23 10:55:15 +00001128 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001129 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001130 if (!OptionName.empty())
1131 OptionName += ',';
1132 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001133 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001134 } else if (Info.getID() == diag::fatal_too_many_errors) {
1135 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001136 } else {
1137 // If the diagnostic is an extension diagnostic and not enabled by default
1138 // then it must have been turned on with -pedantic.
1139 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001140 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1141 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001142 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001143 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001144 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001145 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001146
1147 // If the user wants to see category information, include it too.
1148 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001149 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001150 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001151
Chris Lattnerc9b88902010-05-04 21:13:21 +00001152 // If there is any categorization information, include it.
1153 if (!OptionName.empty() || DiagCategory != 0) {
1154 bool NeedsComma = false;
1155 OutStr += " [";
1156
1157 if (!OptionName.empty()) {
1158 OutStr += OptionName;
1159 NeedsComma = true;
1160 }
1161
1162 if (DiagCategory) {
1163 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001164 if (DiagOpts->ShowCategories == 1)
1165 OutStr += llvm::utostr(DiagCategory);
1166 else {
1167 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001168 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001169 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001170 }
1171
1172 OutStr += "]";
1173 }
1174
1175
Daniel Dunbareace8742009-11-04 06:24:30 +00001176 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001177 // Print warnings, errors and fatal errors in bold, no color
1178 switch (Level) {
1179 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1180 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1181 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1182 default: break; //don't bold notes
1183 }
1184 }
1185
Daniel Dunbareace8742009-11-04 06:24:30 +00001186 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001187 // We will be word-wrapping the error message, so compute the
1188 // column number where we currently are (after printing the
1189 // location information).
1190 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001191 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001192 } else {
1193 OS.write(OutStr.begin(), OutStr.size());
1194 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001195 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001196 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001197 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001198
Douglas Gregordf667e72009-03-10 20:44:00 +00001199 // If caret diagnostics are enabled and we have location, we want to
1200 // emit the caret. However, we only do this if the location moved
1201 // from the last diagnostic, if the last diagnostic was a note that
1202 // was part of a different warning or error diagnostic, or if the
1203 // diagnostic has ranges. We don't want to emit the same caret
1204 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001205 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001206 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001207 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001208 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001209 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001210 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001211 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001212
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001213 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001214 SmallVector<CharSourceRange, 20> Ranges;
1215 Ranges.reserve(Info.getNumRanges());
1216 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1217 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001218
Chandler Carruth5182a182011-09-07 01:47:09 +00001219 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001220 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001221 if (Hint.RemoveRange.isValid())
1222 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001223 }
1224
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001225 const SourceManager &SM = LastLoc.getManager();
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001226 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1227 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001228 // Compute the length of the macro-expansion backtrace, so that we
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001229 // can establish which steps in the macro backtrace we'll skip.
1230 SourceLocation Loc = LastLoc;
1231 unsigned Depth = 0;
1232 do {
1233 ++Depth;
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001234 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001235 Loc = getImmediateMacroCallerLoc(SM, Loc);
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001236 } while (!Loc.isFileID());
1237
1238 if (Depth > DiagOpts->MacroBacktraceLimit) {
1239 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1240 DiagOpts->MacroBacktraceLimit % 2;
1241 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1242 }
1243 }
1244
Chandler Carruth5182a182011-09-07 01:47:09 +00001245 EmitCaretDiagnostic(LastLoc, Ranges, LastLoc.getManager(),
Chandler Carruth8a7b3f72011-09-06 22:31:44 +00001246 llvm::makeArrayRef(Info.getFixItHints(),
1247 Info.getNumFixItHints()),
Chandler Carruth50c909b2011-08-31 23:59:23 +00001248 DiagOpts->MessageLength,
1249 MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001250 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001251
Chris Lattnera03a5b52008-11-19 06:56:25 +00001252 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001253}