blob: 762a7c528c1e19168195cb3af9c316b41468e2c7 [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"
Chris Lattnerf4c83962008-11-19 06:51:40 +000021#include "llvm/ADT/SmallString.h"
Chris Lattnerc9b88902010-05-04 21:13:21 +000022#include "llvm/ADT/StringExtras.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000023#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Chris Lattner5f9e2722011-07-23 10:55:15 +000026static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000036// Used for changing only the bold attribute.
Chris Lattner5f9e2722011-07-23 10:55:15 +000037static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
Torok Edwin603fca72009-06-04 07:18:23 +000039
Douglas Gregorfffd93f2009-05-01 21:53:04 +000040/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Chris Lattner5f9e2722011-07-23 10:55:15 +000043TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000044 const DiagnosticOptions &diags,
45 bool _OwnsOutputStream)
Daniel Dunbareace8742009-11-04 06:24:30 +000046 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbaraea36412009-11-11 09:38:24 +000047 LastCaretDiagnosticWasNote(0),
48 OwnsOutputStream(_OwnsOutputStream) {
49}
50
51TextDiagnosticPrinter::~TextDiagnosticPrinter() {
52 if (OwnsOutputStream)
53 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000054}
55
Chandler Carruth0d6b8932011-08-31 23:59:19 +000056/// \brief Helper to recursivly walk up the include stack and print each layer
57/// on the way back down.
58static void PrintIncludeStackRecursively(raw_ostream &OS,
59 const SourceManager &SM,
60 SourceLocation Loc,
61 bool ShowLocation) {
62 if (Loc.isInvalid())
63 return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000064
Chris Lattnerb9c3f962009-01-27 07:57:44 +000065 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000066 if (PLoc.isInvalid())
67 return;
Chris Lattner5ce24c82009-04-21 03:57:54 +000068
Chandler Carruth0d6b8932011-08-31 23:59:19 +000069 // Print out the other include frames first.
70 PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
71
72 if (ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000073 OS << "In file included from " << PLoc.getFilename()
74 << ':' << PLoc.getLine() << ":\n";
75 else
76 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000077}
78
Chandler Carruth0d6b8932011-08-31 23:59:19 +000079/// \brief Prints an include stack when appropriate for a particular diagnostic
80/// level and location.
81///
82/// This routine handles all the logic of suppressing particular include stacks
83/// (such as those for notes) and duplicate include stacks when repeated
84/// warnings occur within the same file. It also handles the logic of
85/// customizing the formatting and display of the include stack.
86///
87/// \param Level The diagnostic level of the message this stack pertains to.
88/// \param Loc The include location of the current file (not the diagnostic
89/// location).
90void TextDiagnosticPrinter::PrintIncludeStack(Diagnostic::Level Level,
91 SourceLocation Loc,
92 const SourceManager &SM) {
93 // Skip redundant include stacks altogether.
94 if (LastWarningLoc == Loc)
95 return;
96 LastWarningLoc = Loc;
97
98 if (!DiagOpts->ShowNoteIncludeStack && Level == Diagnostic::Note)
99 return;
100
101 PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
102}
103
Douglas Gregor47f71772009-05-01 23:32:58 +0000104/// \brief When the source code line we want to print is too long for
105/// the terminal, select the "interesting" region.
106static void SelectInterestingSourceRegion(std::string &SourceLine,
107 std::string &CaretLine,
108 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000109 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000110 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000111 unsigned MaxSize = std::max(SourceLine.size(),
112 std::max(CaretLine.size(),
113 FixItInsertionLine.size()));
114 if (MaxSize > SourceLine.size())
115 SourceLine.resize(MaxSize, ' ');
116 if (MaxSize > CaretLine.size())
117 CaretLine.resize(MaxSize, ' ');
118 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
119 FixItInsertionLine.resize(MaxSize, ' ');
120
Douglas Gregor47f71772009-05-01 23:32:58 +0000121 // Find the slice that we need to display the full caret line
122 // correctly.
123 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
124 for (; CaretStart != CaretEnd; ++CaretStart)
125 if (!isspace(CaretLine[CaretStart]))
126 break;
127
128 for (; CaretEnd != CaretStart; --CaretEnd)
129 if (!isspace(CaretLine[CaretEnd - 1]))
130 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000131
132 // Make sure we don't chop the string shorter than the caret token
133 // itself.
134 if (CaretEnd < EndOfCaretToken)
135 CaretEnd = EndOfCaretToken;
136
Douglas Gregor844da342009-05-03 04:33:32 +0000137 // If we have a fix-it line, make sure the slice includes all of the
138 // fix-it information.
139 if (!FixItInsertionLine.empty()) {
140 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
141 for (; FixItStart != FixItEnd; ++FixItStart)
142 if (!isspace(FixItInsertionLine[FixItStart]))
143 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000144
Douglas Gregor844da342009-05-03 04:33:32 +0000145 for (; FixItEnd != FixItStart; --FixItEnd)
146 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
147 break;
148
149 if (FixItStart < CaretStart)
150 CaretStart = FixItStart;
151 if (FixItEnd > CaretEnd)
152 CaretEnd = FixItEnd;
153 }
154
Douglas Gregor47f71772009-05-01 23:32:58 +0000155 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
156 // parts of the caret line. While this slice is smaller than the
157 // number of columns we have, try to grow the slice to encompass
158 // more context.
159
160 // If the end of the interesting region comes before we run out of
161 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000162 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000163 CaretStart = 0;
164
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000165 unsigned TargetColumns = Columns;
166 if (TargetColumns > 8)
167 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000168 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000169 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000170 bool ExpandedRegion = false;
171 // Move the start of the interesting region left until we've
172 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000173 if (CaretStart == 1)
174 CaretStart = 0;
175 else if (CaretStart > 1) {
176 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000177
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000178 // Skip over any whitespace we see here; we're looking for
179 // another bit of interesting text.
180 while (NewStart && isspace(SourceLine[NewStart]))
181 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000182
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000183 // Skip over this bit of "interesting" text.
184 while (NewStart && !isspace(SourceLine[NewStart]))
185 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000186
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000187 // Move up to the non-whitespace character we just saw.
188 if (NewStart)
189 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000190
191 // If we're still within our limit, update the starting
192 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000193 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000194 CaretStart = NewStart;
195 ExpandedRegion = true;
196 }
197 }
198
199 // Move the end of the interesting region right until we've
200 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000201 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000202 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000203 unsigned NewEnd = CaretEnd;
204
205 // Skip over any whitespace we see here; we're looking for
206 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000207 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000208 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000209
Douglas Gregor47f71772009-05-01 23:32:58 +0000210 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000211 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000212 ++NewEnd;
213
214 if (NewEnd - CaretStart <= TargetColumns) {
215 CaretEnd = NewEnd;
216 ExpandedRegion = true;
217 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000218 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000219
220 if (!ExpandedRegion)
221 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000222 }
223
224 // [CaretStart, CaretEnd) is the slice we want. Update the various
225 // output lines to show only this slice, with two-space padding
226 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000227 if (CaretEnd < SourceLine.size())
228 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000229 if (CaretEnd < CaretLine.size())
230 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000231 if (FixItInsertionLine.size() > CaretEnd)
232 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000233
Douglas Gregor47f71772009-05-01 23:32:58 +0000234 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000235 SourceLine.replace(0, CaretStart, " ...");
236 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000237 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000238 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000239 }
240}
241
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000242/// Look through spelling locations for a macro argument expansion, and
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000243/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000244/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000245/// don't skip anything and return the starting location.
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000246static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000247 SourceLocation StartLoc) {
248 for (SourceLocation L = StartLoc; L.isMacroID();
249 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruth96d35892011-07-26 03:03:00 +0000250 if (SM.isMacroArgExpansion(L))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000251 return L;
252 }
253
254 // Otherwise just return initial location, there's nothing to skip.
255 return StartLoc;
256}
257
258/// Gets the location of the immediate macro caller, one level up the stack
259/// toward the initial macro typed into the source.
260static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
261 SourceLocation Loc) {
262 if (!Loc.isMacroID()) return Loc;
263
264 // When we have the location of (part of) an expanded parameter, its spelling
265 // location points to the argument as typed into the macro call, and
266 // therefore is used to locate the macro caller.
Chandler Carruth96d35892011-07-26 03:03:00 +0000267 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000268 return SM.getImmediateSpellingLoc(Loc);
269
270 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000271 // expanded (while the spelling is part of the macro definition).
Chandler Carruth999f7392011-07-25 20:52:21 +0000272 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000273}
274
275/// Gets the location of the immediate macro callee, one level down the stack
276/// toward the leaf macro.
277static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
278 SourceLocation Loc) {
279 if (!Loc.isMacroID()) return Loc;
280
281 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000282 // expansion location points to the unexpanded paramater reference within
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000283 // the macro definition (or callee).
Chandler Carruth96d35892011-07-26 03:03:00 +0000284 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth999f7392011-07-25 20:52:21 +0000285 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000286
287 // Otherwise, the callee of the macro is located where this location was
288 // spelled inside the macro definition.
289 return SM.getImmediateSpellingLoc(Loc);
290}
291
Chandler Carruth50c909b2011-08-31 23:59:23 +0000292namespace {
293
294/// \brief Class to encapsulate the logic for printing a caret diagnostic
295/// message.
296///
297/// This class provides an interface for building and emitting a caret
298/// diagnostic, including all of the macro backtrace caret diagnostics, FixIt
299/// Hints, and code snippets. In the presence of macros this turns into
300/// a recursive process and so the class provides common state across the
301/// emission of a particular diagnostic, while each invocation of \see Emit()
302/// walks down the macro stack.
303///
304/// This logic assumes that the core diagnostic location and text has already
305/// been emitted and focuses on emitting the pretty caret display and macro
306/// backtrace following that.
307///
308/// FIXME: Hoist helper routines specific to caret diagnostics into class
309/// methods to reduce paramater passing churn.
310class CaretDiagnostic {
311 TextDiagnosticPrinter &Printer;
312 raw_ostream &OS;
313 const SourceManager &SM;
314 const LangOptions &LangOpts;
315 const DiagnosticOptions &DiagOpts;
316 const unsigned Columns, MacroSkipStart, MacroSkipEnd;
317
318public:
319 CaretDiagnostic(TextDiagnosticPrinter &Printer,
320 raw_ostream &OS,
321 const SourceManager &SM,
322 const LangOptions &LangOpts,
323 const DiagnosticOptions &DiagOpts,
324 unsigned Columns,
325 unsigned MacroSkipStart,
326 unsigned MacroSkipEnd)
327 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
328 Columns(Columns), MacroSkipStart(MacroSkipStart),
329 MacroSkipEnd(MacroSkipEnd) {
330 }
331
332 /// \brief Emit the caret diagnostic text.
333 ///
334 /// Walks up the macro expansion stack printing the code snippet, caret,
335 /// underlines and FixItHint display as appropriate at each level. Walk is
336 /// accomplished by calling itself recursively.
337 ///
Chandler Carruth50c909b2011-08-31 23:59:23 +0000338 /// FIXME: Break up massive function into logical units.
339 ///
340 /// \param Loc The location for this caret.
341 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000342 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000343 /// \param OnMacroInst The current depth of the macro expansion stack.
344 void Emit(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000345 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000346 ArrayRef<FixItHint> Hints,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000347 unsigned OnMacroInst = 0) {
348 assert(!Loc.isInvalid() && "must have a valid source location here");
349
350 // If this is a macro ID, first emit information about where this was
351 // expanded (recursively) then emit information about where the token was
352 // spelled from.
353 if (!Loc.isFileID()) {
354 // Whether to suppress printing this macro expansion.
355 bool Suppressed
356 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
357
358 // When processing macros, skip over the expansions leading up to
359 // a macro argument, and trace the argument's expansion stack instead.
360 Loc = skipToMacroArgExpansion(SM, Loc);
361
362 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
363
364 // FIXME: Map ranges?
Chandler Carruth5182a182011-09-07 01:47:09 +0000365 Emit(OneLevelUp, Ranges, Hints, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000366
367 // Map the location.
368 Loc = getImmediateMacroCalleeLoc(SM, Loc);
369
370 // Map the ranges.
Chandler Carruth5182a182011-09-07 01:47:09 +0000371 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
372 E = Ranges.end();
373 I != E; ++I) {
374 SourceLocation Start = I->getBegin(), End = I->getEnd();
375 if (Start.isMacroID())
376 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
377 if (End.isMacroID())
378 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
Chandler Carruth50c909b2011-08-31 23:59:23 +0000379 }
380
381 if (!Suppressed) {
382 // Don't print recursive expansion notes from an expansion note.
383 Loc = SM.getSpellingLoc(Loc);
384
385 // Get the pretty name, according to #line directives etc.
386 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
387 if (PLoc.isInvalid())
388 return;
389
390 // If this diagnostic is not in the main file, print out the
391 // "included from" lines.
392 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
393
394 if (DiagOpts.ShowLocation) {
395 // Emit the file/line/column that this expansion came from.
396 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
397 if (DiagOpts.ShowColumn)
398 OS << PLoc.getColumn() << ':';
399 OS << ' ';
400 }
401 OS << "note: expanded from:\n";
402
Chandler Carruth5182a182011-09-07 01:47:09 +0000403 Emit(Loc, Ranges, ArrayRef<FixItHint>(), OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000404 return;
405 }
406
407 if (OnMacroInst == MacroSkipStart) {
408 // Tell the user that we've skipped contexts.
409 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
410 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
411 "all)\n";
412 }
413
414 return;
415 }
416
417 // Decompose the location into a FID/Offset pair.
418 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
419 FileID FID = LocInfo.first;
420 unsigned FileOffset = LocInfo.second;
421
422 // Get information about the buffer it points into.
423 bool Invalid = false;
424 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
425 if (Invalid)
426 return;
427
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000428 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000429 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
430 unsigned CaretEndColNo
431 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
432
433 // Rewind from the current position to the start of the line.
434 const char *TokPtr = BufStart+FileOffset;
435 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
436
437
438 // Compute the line end. Scan forward from the error position to the end of
439 // the line.
440 const char *LineEnd = TokPtr;
441 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
442 ++LineEnd;
443
444 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
445 // the source line length as currently being computed. See
446 // test/Misc/message-length.c.
447 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
448
449 // Copy the line of code into an std::string for ease of manipulation.
450 std::string SourceLine(LineStart, LineEnd);
451
452 // Create a line for the caret that is filled with spaces that is the same
453 // length as the line of source code.
454 std::string CaretLine(LineEnd-LineStart, ' ');
455
456 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000457 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
458 E = Ranges.end();
459 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000460 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000461
462 // Next, insert the caret itself.
463 if (ColNo-1 < CaretLine.size())
464 CaretLine[ColNo-1] = '^';
465 else
466 CaretLine.push_back('^');
467
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000468 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000469
470 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
471 // to produce easily machine parsable output. Add a space before the
472 // source line and the caret to make it trivial to tell the main diagnostic
473 // line from what the user is intended to see.
474 if (DiagOpts.ShowSourceRanges) {
475 SourceLine = ' ' + SourceLine;
476 CaretLine = ' ' + CaretLine;
477 }
478
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000479 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000480 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000481 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000482
483 // If the source line is too long for our terminal, select only the
484 // "interesting" source region within that line.
485 if (Columns && SourceLine.size() > Columns)
486 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
487 CaretEndColNo, Columns);
488
489 // Finally, remove any blank spaces from the end of CaretLine.
490 while (CaretLine[CaretLine.size()-1] == ' ')
491 CaretLine.erase(CaretLine.end()-1);
492
493 // Emit what we have computed.
494 OS << SourceLine << '\n';
495
496 if (DiagOpts.ShowColors)
497 OS.changeColor(caretColor, true);
498 OS << CaretLine << '\n';
499 if (DiagOpts.ShowColors)
500 OS.resetColor();
501
502 if (!FixItInsertionLine.empty()) {
503 if (DiagOpts.ShowColors)
504 // Print fixit line in color
505 OS.changeColor(fixitColor, false);
506 if (DiagOpts.ShowSourceRanges)
507 OS << ' ';
508 OS << FixItInsertionLine << '\n';
509 if (DiagOpts.ShowColors)
510 OS.resetColor();
511 }
512
Chandler Carruthcca61582011-09-02 06:30:30 +0000513 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000514 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000515 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000516
Chandler Carruthcca61582011-09-02 06:30:30 +0000517private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000518 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
519 void HighlightRange(const CharSourceRange &R,
520 unsigned LineNo, FileID FID,
521 const std::string &SourceLine,
522 std::string &CaretLine) {
523 assert(CaretLine.size() == SourceLine.size() &&
524 "Expect a correspondence between source and caret line!");
525 if (!R.isValid()) return;
526
527 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
528 SourceLocation End = SM.getExpansionLoc(R.getEnd());
529
530 // If the End location and the start location are the same and are a macro
531 // location, then the range was something that came from a macro expansion
532 // or _Pragma. If this is an object-like macro, the best we can do is to
533 // highlight the range. If this is a function-like macro, we'd also like to
534 // highlight the arguments.
535 if (Begin == End && R.getEnd().isMacroID())
536 End = SM.getExpansionRange(R.getEnd()).second;
537
538 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
539 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
540 return; // No intersection.
541
542 unsigned EndLineNo = SM.getExpansionLineNumber(End);
543 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
544 return; // No intersection.
545
546 // Compute the column number of the start.
547 unsigned StartColNo = 0;
548 if (StartLineNo == LineNo) {
549 StartColNo = SM.getExpansionColumnNumber(Begin);
550 if (StartColNo) --StartColNo; // Zero base the col #.
551 }
552
553 // Compute the column number of the end.
554 unsigned EndColNo = CaretLine.size();
555 if (EndLineNo == LineNo) {
556 EndColNo = SM.getExpansionColumnNumber(End);
557 if (EndColNo) {
558 --EndColNo; // Zero base the col #.
559
560 // Add in the length of the token, so that we cover multi-char tokens if
561 // this is a token range.
562 if (R.isTokenRange())
563 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
564 } else {
565 EndColNo = CaretLine.size();
566 }
567 }
568
569 assert(StartColNo <= EndColNo && "Invalid range!");
570
571 // Check that a token range does not highlight only whitespace.
572 if (R.isTokenRange()) {
573 // Pick the first non-whitespace column.
574 while (StartColNo < SourceLine.size() &&
575 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
576 ++StartColNo;
577
578 // Pick the last non-whitespace column.
579 if (EndColNo > SourceLine.size())
580 EndColNo = SourceLine.size();
581 while (EndColNo-1 &&
582 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
583 --EndColNo;
584
585 // If the start/end passed each other, then we are trying to highlight a
586 // range that just exists in whitespace, which must be some sort of other
587 // bug.
588 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
589 }
590
591 // Fill the range with ~'s.
592 for (unsigned i = StartColNo; i < EndColNo; ++i)
593 CaretLine[i] = '~';
594 }
595
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000596 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000597 const char *LineStart,
598 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000599 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000600 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000601 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000602 return FixItInsertionLine;
603
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000604 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
605 I != E; ++I) {
606 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000607 // We have an insertion hint. Determine whether the inserted
608 // code is on the same line as the caret.
609 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000610 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000611 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000612 // Insert the new code into the line just below the code
613 // that the user wrote.
614 unsigned HintColNo
615 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
616 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000617 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000618 if (LastColumnModified > FixItInsertionLine.size())
619 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000620 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000621 FixItInsertionLine.begin() + HintColNo - 1);
622 } else {
623 FixItInsertionLine.clear();
624 break;
625 }
626 }
627 }
628
629 if (FixItInsertionLine.empty())
630 return FixItInsertionLine;
631
632 // Now that we have the entire fixit line, expand the tabs in it.
633 // Since we don't want to insert spaces in the middle of a word,
634 // find each word and the column it should line up with and insert
635 // spaces until they match.
636 unsigned FixItPos = 0;
637 unsigned LinePos = 0;
638 unsigned TabExpandedCol = 0;
639 unsigned LineLength = LineEnd - LineStart;
640
641 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
642 // Find the next word in the FixIt line.
643 while (FixItPos < FixItInsertionLine.size() &&
644 FixItInsertionLine[FixItPos] == ' ')
645 ++FixItPos;
646 unsigned CharDistance = FixItPos - TabExpandedCol;
647
648 // Walk forward in the source line, keeping track of
649 // the tab-expanded column.
650 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
651 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
652 ++TabExpandedCol;
653 else
654 TabExpandedCol =
655 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
656
657 // Adjust the fixit line to match this column.
658 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
659 FixItPos = TabExpandedCol;
660
661 // Walk to the end of the word.
662 while (FixItPos < FixItInsertionLine.size() &&
663 FixItInsertionLine[FixItPos] != ' ')
664 ++FixItPos;
665 }
666
667 return FixItInsertionLine;
668 }
669
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000670 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
671 // Scan the source line, looking for tabs. If we find any, manually expand
672 // them to spaces and update the CaretLine to match.
673 for (unsigned i = 0; i != SourceLine.size(); ++i) {
674 if (SourceLine[i] != '\t') continue;
675
676 // Replace this tab with at least one space.
677 SourceLine[i] = ' ';
678
679 // Compute the number of spaces we need to insert.
680 unsigned TabStop = DiagOpts.TabStop;
681 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
682 "Invalid -ftabstop value");
683 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
684 assert(NumSpaces < TabStop && "Invalid computation of space amt");
685
686 // Insert spaces into the SourceLine.
687 SourceLine.insert(i+1, NumSpaces, ' ');
688
689 // Insert spaces or ~'s into CaretLine.
690 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
691 }
692 }
693
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000694 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000695 if (!DiagOpts.ShowParseableFixits)
696 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000697
Chandler Carruthcca61582011-09-02 06:30:30 +0000698 // We follow FixItRewriter's example in not (yet) handling
699 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000700 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
701 I != E; ++I) {
702 if (I->RemoveRange.isInvalid() ||
703 I->RemoveRange.getBegin().isMacroID() ||
704 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000705 return;
706 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000707
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000708 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
709 I != E; ++I) {
710 SourceLocation BLoc = I->RemoveRange.getBegin();
711 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000712
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000713 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
714 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000715
Chandler Carruthcca61582011-09-02 06:30:30 +0000716 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000717 if (I->RemoveRange.isTokenRange())
718 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000719
Chandler Carruthcca61582011-09-02 06:30:30 +0000720 // We specifically do not do word-wrapping or tab-expansion here,
721 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000722 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000723 if (PLoc.isInvalid())
724 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000725
Chandler Carruthcca61582011-09-02 06:30:30 +0000726 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000727 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000728 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
729 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
730 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
731 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
732 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000733 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000734 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000735 }
736 }
737};
738
739} // end namespace
740
Chandler Carruth5182a182011-09-07 01:47:09 +0000741void TextDiagnosticPrinter::EmitCaretDiagnostic(
742 SourceLocation Loc,
743 SmallVectorImpl<CharSourceRange>& Ranges,
744 const SourceManager &SM,
745 ArrayRef<FixItHint> Hints,
746 unsigned Columns,
747 unsigned MacroSkipStart,
748 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000749 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chandler Carruth50c909b2011-08-31 23:59:23 +0000750 assert(DiagOpts && "Unexpected diagnostic without options set");
751 // FIXME: Remove this method and have clients directly build and call Emit on
752 // the CaretDiagnostic object.
753 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts,
754 Columns, MacroSkipStart, MacroSkipEnd);
Chandler Carruth5182a182011-09-07 01:47:09 +0000755 CaretDiag.Emit(Loc, Ranges, Hints);
Chris Lattner94f55782009-02-17 07:38:37 +0000756}
757
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000758/// \brief Skip over whitespace in the string, starting at the given
759/// index.
760///
761/// \returns The index of the first non-whitespace character that is
762/// greater than or equal to Idx or, if no such character exists,
763/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000764static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000765 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000766 unsigned Length) {
767 while (Idx < Length && isspace(Str[Idx]))
768 ++Idx;
769 return Idx;
770}
771
772/// \brief If the given character is the start of some kind of
773/// balanced punctuation (e.g., quotes or parentheses), return the
774/// character that will terminate the punctuation.
775///
776/// \returns The ending punctuation character, if any, or the NULL
777/// character if the input character does not start any punctuation.
778static inline char findMatchingPunctuation(char c) {
779 switch (c) {
780 case '\'': return '\'';
781 case '`': return '\'';
782 case '"': return '"';
783 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000784 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000785 case '{': return '}';
786 default: break;
787 }
788
789 return 0;
790}
791
792/// \brief Find the end of the word starting at the given offset
793/// within a string.
794///
795/// \returns the index pointing one character past the end of the
796/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000797static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000798 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000799 unsigned Length, unsigned Column,
800 unsigned Columns) {
801 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000802 unsigned End = Start + 1;
803
Daniel Dunbareae18f82009-12-06 09:56:18 +0000804 // If we are already at the end of the string, take that as the word.
805 if (End == Str.size())
806 return End;
807
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000808 // Determine if the start of the string is actually opening
809 // punctuation, e.g., a quote or parentheses.
810 char EndPunct = findMatchingPunctuation(Str[Start]);
811 if (!EndPunct) {
812 // This is a normal word. Just find the first space character.
813 while (End < Length && !isspace(Str[End]))
814 ++End;
815 return End;
816 }
817
818 // We have the start of a balanced punctuation sequence (quotes,
819 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000820 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000821 PunctuationEndStack.push_back(EndPunct);
822 while (End < Length && !PunctuationEndStack.empty()) {
823 if (Str[End] == PunctuationEndStack.back())
824 PunctuationEndStack.pop_back();
825 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
826 PunctuationEndStack.push_back(SubEndPunct);
827
828 ++End;
829 }
830
831 // Find the first space character after the punctuation ended.
832 while (End < Length && !isspace(Str[End]))
833 ++End;
834
835 unsigned PunctWordLength = End - Start;
836 if (// If the word fits on this line
837 Column + PunctWordLength <= Columns ||
838 // ... or the word is "short enough" to take up the next line
839 // without too much ugly white space
840 PunctWordLength < Columns/3)
841 return End; // Take the whole thing as a single "word".
842
843 // The whole quoted/parenthesized string is too long to print as a
844 // single "word". Instead, find the "word" that starts just after
845 // the punctuation and use that end-point instead. This will recurse
846 // until it finds something small enough to consider a word.
847 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
848}
849
850/// \brief Print the given string to a stream, word-wrapping it to
851/// some number of columns in the process.
852///
853/// \brief OS the stream to which the word-wrapping string will be
854/// emitted.
855///
856/// \brief Str the string to word-wrap and output.
857///
858/// \brief Columns the number of columns to word-wrap to.
859///
860/// \brief Column the column number at which the first character of \p
861/// Str will be printed. This will be non-zero when part of the first
862/// line has already been printed.
863///
864/// \brief Indentation the number of spaces to indent any lines beyond
865/// the first line.
866///
867/// \returns true if word-wrapping was required, or false if the
868/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000869static bool PrintWordWrapped(raw_ostream &OS,
870 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000871 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000872 unsigned Column = 0,
873 unsigned Indentation = WordWrapIndentation) {
874 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000875
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000876 // If there is a newline in this message somewhere, find that
877 // newline and split the message into the part before the newline
878 // (which will be word-wrapped) and the part from the newline one
879 // (which will be emitted unchanged).
880 for (unsigned I = 0; I != Length; ++I)
881 if (Str[I] == '\n') {
882 Length = I;
883 break;
884 }
885
886 // The string used to indent each line.
887 llvm::SmallString<16> IndentStr;
888 IndentStr.assign(Indentation, ' ');
889 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000890 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000891 WordStart = WordEnd) {
892 // Find the beginning of the next word.
893 WordStart = skipWhitespace(WordStart, Str, Length);
894 if (WordStart == Length)
895 break;
896
897 // Find the end of this word.
898 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000899
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000900 // Does this word fit on the current line?
901 unsigned WordLength = WordEnd - WordStart;
902 if (Column + WordLength < Columns) {
903 // This word fits on the current line; print it there.
904 if (WordStart) {
905 OS << ' ';
906 Column += 1;
907 }
908 OS.write(&Str[WordStart], WordLength);
909 Column += WordLength;
910 continue;
911 }
912
913 // This word does not fit on the current line, so wrap to the next
914 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000915 OS << '\n';
916 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000917 OS.write(&Str[WordStart], WordLength);
918 Column = Indentation + WordLength;
919 Wrapped = true;
920 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000921
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000922 if (Length == Str.size())
923 return Wrapped; // We're done.
924
925 // There is a newline in the message, followed by something that
926 // will not be word-wrapped. Print that.
927 OS.write(&Str[Length], Str.size() - Length);
928 return true;
929}
Chris Lattner94f55782009-02-17 07:38:37 +0000930
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000931/// Get the presumed location of a diagnostic message. This computes the
932/// presumed location for the top of any macro backtrace when present.
933static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
934 SourceLocation Loc) {
935 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
936 // walk to the top of the macro call stack.
937 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000938 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000939 Loc = getImmediateMacroCallerLoc(SM, Loc);
940 }
941
942 return SM.getPresumedLoc(Loc);
943}
944
Chandler Carruth5770bb72011-09-07 08:05:58 +0000945/// \brief Print out the file/line/column information and include trace.
946///
947/// This method handlen the emission of the diagnostic location information.
948/// This includes extracting as much location information as is present for the
949/// diagnostic and printing it, as well as any include stack or source ranges
950/// necessary.
951void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
952 const DiagnosticInfo &Info,
953 const SourceManager &SM,
954 PresumedLoc PLoc) {
955 if (PLoc.isInvalid()) {
956 // At least print the file name if available:
957 FileID FID = SM.getFileID(Info.getLocation());
958 if (!FID.isInvalid()) {
959 const FileEntry* FE = SM.getFileEntryForID(FID);
960 if (FE && FE->getName()) {
961 OS << FE->getName();
962 if (FE->getDevice() == 0 && FE->getInode() == 0
963 && FE->getFileMode() == 0) {
964 // in PCH is a guess, but a good one:
965 OS << " (in PCH)";
966 }
967 OS << ": ";
968 }
969 }
970 return;
971 }
972 unsigned LineNo = PLoc.getLine();
973
974 if (!DiagOpts->ShowLocation)
975 return;
976
977 if (DiagOpts->ShowColors)
978 OS.changeColor(savedColor, true);
979
980 OS << PLoc.getFilename();
981 switch (DiagOpts->Format) {
982 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
983 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
984 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
985 }
986
987 if (DiagOpts->ShowColumn)
988 // Compute the column number.
989 if (unsigned ColNo = PLoc.getColumn()) {
990 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
991 OS << ',';
992 ColNo--;
993 } else
994 OS << ':';
995 OS << ColNo;
996 }
997 switch (DiagOpts->Format) {
998 case DiagnosticOptions::Clang:
999 case DiagnosticOptions::Vi: OS << ':'; break;
1000 case DiagnosticOptions::Msvc: OS << ") : "; break;
1001 }
1002
1003 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1004 FileID CaretFileID =
1005 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1006 bool PrintedRange = false;
1007
1008 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1009 // Ignore invalid ranges.
1010 if (!Info.getRange(i).isValid()) continue;
1011
1012 SourceLocation B = Info.getRange(i).getBegin();
1013 SourceLocation E = Info.getRange(i).getEnd();
1014 B = SM.getExpansionLoc(B);
1015 E = SM.getExpansionLoc(E);
1016
1017 // If the End location and the start location are the same and are a
1018 // macro location, then the range was something that came from a
1019 // macro expansion or _Pragma. If this is an object-like macro, the
1020 // best we can do is to highlight the range. If this is a
1021 // function-like macro, we'd also like to highlight the arguments.
1022 if (B == E && Info.getRange(i).getEnd().isMacroID())
1023 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1024
1025 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1026 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1027
1028 // If the start or end of the range is in another file, just discard
1029 // it.
1030 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1031 continue;
1032
1033 // Add in the length of the token, so that we cover multi-char
1034 // tokens.
1035 unsigned TokSize = 0;
1036 if (Info.getRange(i).isTokenRange())
1037 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1038
1039 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1040 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1041 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1042 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1043 << '}';
1044 PrintedRange = true;
1045 }
1046
1047 if (PrintedRange)
1048 OS << ':';
1049 }
1050 OS << ' ';
1051}
1052
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001053void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +00001054 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +00001055 // Default implementation (Warnings/errors count).
1056 DiagnosticClient::HandleDiagnostic(Level, Info);
1057
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001058 // Keeps track of the the starting position of the location
1059 // information (e.g., "foo.c:10:4:") that precedes the error
1060 // message. We use this information to determine how long the
1061 // file+line+column number prefix is.
1062 uint64_t StartOfLocationInfo = OS.tell();
1063
Daniel Dunbarb96b6702010-02-25 03:23:40 +00001064 if (!Prefix.empty())
1065 OS << Prefix << ": ";
1066
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001067 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001068 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001069 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001070
Chandler Carruth5770bb72011-09-07 08:05:58 +00001071 // First, if this diagnostic is not in the main file, print out the
1072 // "included from" lines.
1073 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1074 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +00001075
Chandler Carruth5770bb72011-09-07 08:05:58 +00001076 // Next emit the location of this particular diagnostic.
1077 EmitDiagnosticLoc(Level, Info, SM, PLoc);
Axel Naumann04331162011-01-27 10:55:51 +00001078
Chandler Carruth5770bb72011-09-07 08:05:58 +00001079 if (DiagOpts->ShowColors)
1080 OS.resetColor();
Torok Edwin603fca72009-06-04 07:18:23 +00001081 }
1082
Daniel Dunbareace8742009-11-04 06:24:30 +00001083 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001084 // Print diagnostic category in bold and color
1085 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001086 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Torok Edwin603fca72009-06-04 07:18:23 +00001087 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1088 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1089 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1090 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001091 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001092 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001093
Reid Spencer5f016e22007-07-11 17:01:13 +00001094 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001095 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001096 case Diagnostic::Note: OS << "note: "; break;
1097 case Diagnostic::Warning: OS << "warning: "; break;
1098 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001099 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 }
Torok Edwin603fca72009-06-04 07:18:23 +00001101
Daniel Dunbareace8742009-11-04 06:24:30 +00001102 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001103 OS.resetColor();
1104
Chris Lattnerf4c83962008-11-19 06:51:40 +00001105 llvm::SmallString<100> OutStr;
1106 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001107
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001108 if (DiagOpts->ShowNames &&
1109 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1110 OutStr += " [";
1111 OutStr += DiagnosticIDs::getName(Info.getID());
1112 OutStr += "]";
1113 }
1114
Chris Lattnerc9b88902010-05-04 21:13:21 +00001115 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001116 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001117 // Was this a warning mapped to an error using -Werror or pragma?
1118 if (Level == Diagnostic::Error &&
1119 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1120 diag::Mapping mapping = diag::MAP_IGNORE;
1121 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1122 &mapping);
1123 if (mapping == diag::MAP_WARNING)
1124 OptionName += "-Werror";
1125 }
1126
Chris Lattner5f9e2722011-07-23 10:55:15 +00001127 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001128 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001129 if (!OptionName.empty())
1130 OptionName += ',';
1131 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001132 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001133 } else if (Info.getID() == diag::fatal_too_many_errors) {
1134 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001135 } else {
1136 // If the diagnostic is an extension diagnostic and not enabled by default
1137 // then it must have been turned on with -pedantic.
1138 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001139 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1140 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001141 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001142 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001143 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001144 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001145
1146 // If the user wants to see category information, include it too.
1147 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001148 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001149 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001150
Chris Lattnerc9b88902010-05-04 21:13:21 +00001151 // If there is any categorization information, include it.
1152 if (!OptionName.empty() || DiagCategory != 0) {
1153 bool NeedsComma = false;
1154 OutStr += " [";
1155
1156 if (!OptionName.empty()) {
1157 OutStr += OptionName;
1158 NeedsComma = true;
1159 }
1160
1161 if (DiagCategory) {
1162 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001163 if (DiagOpts->ShowCategories == 1)
1164 OutStr += llvm::utostr(DiagCategory);
1165 else {
1166 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001167 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001168 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001169 }
1170
1171 OutStr += "]";
1172 }
1173
1174
Daniel Dunbareace8742009-11-04 06:24:30 +00001175 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001176 // Print warnings, errors and fatal errors in bold, no color
1177 switch (Level) {
1178 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1179 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1180 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1181 default: break; //don't bold notes
1182 }
1183 }
1184
Daniel Dunbareace8742009-11-04 06:24:30 +00001185 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001186 // We will be word-wrapping the error message, so compute the
1187 // column number where we currently are (after printing the
1188 // location information).
1189 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001190 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001191 } else {
1192 OS.write(OutStr.begin(), OutStr.size());
1193 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001194 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001195 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001196 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001197
Douglas Gregordf667e72009-03-10 20:44:00 +00001198 // If caret diagnostics are enabled and we have location, we want to
1199 // emit the caret. However, we only do this if the location moved
1200 // from the last diagnostic, if the last diagnostic was a note that
1201 // was part of a different warning or error diagnostic, or if the
1202 // diagnostic has ranges. We don't want to emit the same caret
1203 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001204 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001205 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001206 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001207 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001208 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001209 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001210 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001211
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001212 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001213 SmallVector<CharSourceRange, 20> Ranges;
1214 Ranges.reserve(Info.getNumRanges());
1215 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1216 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001217
Chandler Carruth5182a182011-09-07 01:47:09 +00001218 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001219 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001220 if (Hint.RemoveRange.isValid())
1221 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001222 }
1223
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001224 const SourceManager &SM = LastLoc.getManager();
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001225 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1226 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001227 // Compute the length of the macro-expansion backtrace, so that we
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001228 // can establish which steps in the macro backtrace we'll skip.
1229 SourceLocation Loc = LastLoc;
1230 unsigned Depth = 0;
1231 do {
1232 ++Depth;
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001233 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001234 Loc = getImmediateMacroCallerLoc(SM, Loc);
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001235 } while (!Loc.isFileID());
1236
1237 if (Depth > DiagOpts->MacroBacktraceLimit) {
1238 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1239 DiagOpts->MacroBacktraceLimit % 2;
1240 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1241 }
1242 }
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(),
1246 Info.getNumFixItHints()),
Chandler Carruth50c909b2011-08-31 23:59:23 +00001247 DiagOpts->MessageLength,
1248 MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001250
Chris Lattnera03a5b52008-11-19 06:56:25 +00001251 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001252}