blob: 34dad73e1e0f9b136f2b51f8660c44aa67271fad [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
Chandler Carruth18fc0022011-09-25 22:54:56 +0000295/// \brief Class to encapsulate the logic for formatting and printing a textual
296/// diagnostic message.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000297///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000298/// This class provides an interface for building and emitting a textual
299/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
300/// Hints, and code snippets. In the presence of macros this involves
301/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000302///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000303/// The purpose of this class is to isolate the implementation of printing
304/// beautiful text diagnostics from any particular interfaces. The Clang
305/// DiagnosticClient is implemented through this class as is diagnostic
306/// printing coming out of libclang.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000307///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000308/// A brief worklist:
309/// FIXME: Sink the printing of the diagnostic message itself into this class.
310/// FIXME: Sink the printing of the include stack into this class.
311/// FIXME: Remove the TextDiagnosticPrinter as an input.
312/// FIXME: Sink the recursive printing of template instantiations into this
313/// class.
314class TextDiagnostic {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000315 TextDiagnosticPrinter &Printer;
316 raw_ostream &OS;
317 const SourceManager &SM;
318 const LangOptions &LangOpts;
319 const DiagnosticOptions &DiagOpts;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000320
321public:
Chandler Carruth18fc0022011-09-25 22:54:56 +0000322 TextDiagnostic(TextDiagnosticPrinter &Printer,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000323 raw_ostream &OS,
324 const SourceManager &SM,
325 const LangOptions &LangOpts,
Chandler Carruth8be5c152011-09-25 22:31:58 +0000326 const DiagnosticOptions &DiagOpts)
327 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts) {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000328 }
329
330 /// \brief Emit the caret diagnostic text.
331 ///
332 /// Walks up the macro expansion stack printing the code snippet, caret,
333 /// underlines and FixItHint display as appropriate at each level. Walk is
334 /// accomplished by calling itself recursively.
335 ///
Chandler Carruth50c909b2011-08-31 23:59:23 +0000336 /// FIXME: Break up massive function into logical units.
337 ///
338 /// \param Loc The location for this caret.
339 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000340 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000341 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000342 /// \param OnMacroInst The current depth of the macro expansion stack.
343 void Emit(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000344 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000345 ArrayRef<FixItHint> Hints,
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000346 unsigned &MacroDepth,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000347 unsigned OnMacroInst = 0) {
348 assert(!Loc.isInvalid() && "must have a valid source location here");
349
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000350 // If this is a file source location, directly emit the source snippet and
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000351 // caret line. Also record the macro depth reached.
352 if (Loc.isFileID()) {
353 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
354 MacroDepth = OnMacroInst;
355 EmitSnippetAndCaret(Loc, Ranges, Hints);
356 return;
357 }
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000358 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000359
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000360 // When processing macros, skip over the expansions leading up to
361 // a macro argument, and trace the argument's expansion stack instead.
362 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000363
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000364 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000365
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000366 // FIXME: Map ranges?
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000367 Emit(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000368
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000369 // Map the location.
370 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000371
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000372 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
373 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
374 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
375 DiagOpts.MacroBacktraceLimit % 2;
376 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
377 }
378
379 // Whether to suppress printing this macro expansion.
380 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
381 OnMacroInst < MacroSkipEnd);
382
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000383 // Map the ranges.
384 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
385 E = Ranges.end();
386 I != E; ++I) {
387 SourceLocation Start = I->getBegin(), End = I->getEnd();
388 if (Start.isMacroID())
389 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
390 if (End.isMacroID())
391 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
392 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000393
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000394 if (!Suppressed) {
395 // Don't print recursive expansion notes from an expansion note.
396 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000397
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000398 // Get the pretty name, according to #line directives etc.
399 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
400 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000401 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000402
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000403 // If this diagnostic is not in the main file, print out the
404 // "included from" lines.
405 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000406
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000407 if (DiagOpts.ShowLocation) {
408 // Emit the file/line/column that this expansion came from.
409 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
410 if (DiagOpts.ShowColumn)
411 OS << PLoc.getColumn() << ':';
412 OS << ' ';
413 }
414 OS << "note: expanded from:\n";
415
416 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000417 return;
418 }
419
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000420 if (OnMacroInst == MacroSkipStart) {
421 // Tell the user that we've skipped contexts.
422 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
423 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
424 "all)\n";
425 }
426 }
427
428 /// \brief Emit a code snippet and caret line.
429 ///
430 /// This routine emits a single line's code snippet and caret line..
431 ///
432 /// \param Loc The location for the caret.
433 /// \param Ranges The underlined ranges for this code snippet.
434 /// \param Hints The FixIt hints active for this diagnostic.
435 void EmitSnippetAndCaret(SourceLocation Loc,
436 SmallVectorImpl<CharSourceRange>& Ranges,
437 ArrayRef<FixItHint> Hints) {
438 assert(!Loc.isInvalid() && "must have a valid source location here");
439 assert(Loc.isFileID() && "must have a file location here");
440
Chandler Carruth50c909b2011-08-31 23:59:23 +0000441 // Decompose the location into a FID/Offset pair.
442 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
443 FileID FID = LocInfo.first;
444 unsigned FileOffset = LocInfo.second;
445
446 // Get information about the buffer it points into.
447 bool Invalid = false;
448 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
449 if (Invalid)
450 return;
451
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000452 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000453 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
454 unsigned CaretEndColNo
455 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
456
457 // Rewind from the current position to the start of the line.
458 const char *TokPtr = BufStart+FileOffset;
459 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
460
461
462 // Compute the line end. Scan forward from the error position to the end of
463 // the line.
464 const char *LineEnd = TokPtr;
465 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
466 ++LineEnd;
467
468 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
469 // the source line length as currently being computed. See
470 // test/Misc/message-length.c.
471 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
472
473 // Copy the line of code into an std::string for ease of manipulation.
474 std::string SourceLine(LineStart, LineEnd);
475
476 // Create a line for the caret that is filled with spaces that is the same
477 // length as the line of source code.
478 std::string CaretLine(LineEnd-LineStart, ' ');
479
480 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000481 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
482 E = Ranges.end();
483 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000484 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000485
486 // Next, insert the caret itself.
487 if (ColNo-1 < CaretLine.size())
488 CaretLine[ColNo-1] = '^';
489 else
490 CaretLine.push_back('^');
491
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000492 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000493
494 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
495 // to produce easily machine parsable output. Add a space before the
496 // source line and the caret to make it trivial to tell the main diagnostic
497 // line from what the user is intended to see.
498 if (DiagOpts.ShowSourceRanges) {
499 SourceLine = ' ' + SourceLine;
500 CaretLine = ' ' + CaretLine;
501 }
502
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000503 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000504 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000505 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000506
507 // If the source line is too long for our terminal, select only the
508 // "interesting" source region within that line.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000509 unsigned Columns = DiagOpts.MessageLength;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000510 if (Columns && SourceLine.size() > Columns)
511 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
512 CaretEndColNo, Columns);
513
514 // Finally, remove any blank spaces from the end of CaretLine.
515 while (CaretLine[CaretLine.size()-1] == ' ')
516 CaretLine.erase(CaretLine.end()-1);
517
518 // Emit what we have computed.
519 OS << SourceLine << '\n';
520
521 if (DiagOpts.ShowColors)
522 OS.changeColor(caretColor, true);
523 OS << CaretLine << '\n';
524 if (DiagOpts.ShowColors)
525 OS.resetColor();
526
527 if (!FixItInsertionLine.empty()) {
528 if (DiagOpts.ShowColors)
529 // Print fixit line in color
530 OS.changeColor(fixitColor, false);
531 if (DiagOpts.ShowSourceRanges)
532 OS << ' ';
533 OS << FixItInsertionLine << '\n';
534 if (DiagOpts.ShowColors)
535 OS.resetColor();
536 }
537
Chandler Carruthcca61582011-09-02 06:30:30 +0000538 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000539 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000540 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000541
Chandler Carruthcca61582011-09-02 06:30:30 +0000542private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000543 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
544 void HighlightRange(const CharSourceRange &R,
545 unsigned LineNo, FileID FID,
546 const std::string &SourceLine,
547 std::string &CaretLine) {
548 assert(CaretLine.size() == SourceLine.size() &&
549 "Expect a correspondence between source and caret line!");
550 if (!R.isValid()) return;
551
552 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
553 SourceLocation End = SM.getExpansionLoc(R.getEnd());
554
555 // If the End location and the start location are the same and are a macro
556 // location, then the range was something that came from a macro expansion
557 // or _Pragma. If this is an object-like macro, the best we can do is to
558 // highlight the range. If this is a function-like macro, we'd also like to
559 // highlight the arguments.
560 if (Begin == End && R.getEnd().isMacroID())
561 End = SM.getExpansionRange(R.getEnd()).second;
562
563 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
564 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
565 return; // No intersection.
566
567 unsigned EndLineNo = SM.getExpansionLineNumber(End);
568 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
569 return; // No intersection.
570
571 // Compute the column number of the start.
572 unsigned StartColNo = 0;
573 if (StartLineNo == LineNo) {
574 StartColNo = SM.getExpansionColumnNumber(Begin);
575 if (StartColNo) --StartColNo; // Zero base the col #.
576 }
577
578 // Compute the column number of the end.
579 unsigned EndColNo = CaretLine.size();
580 if (EndLineNo == LineNo) {
581 EndColNo = SM.getExpansionColumnNumber(End);
582 if (EndColNo) {
583 --EndColNo; // Zero base the col #.
584
585 // Add in the length of the token, so that we cover multi-char tokens if
586 // this is a token range.
587 if (R.isTokenRange())
588 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
589 } else {
590 EndColNo = CaretLine.size();
591 }
592 }
593
594 assert(StartColNo <= EndColNo && "Invalid range!");
595
596 // Check that a token range does not highlight only whitespace.
597 if (R.isTokenRange()) {
598 // Pick the first non-whitespace column.
599 while (StartColNo < SourceLine.size() &&
600 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
601 ++StartColNo;
602
603 // Pick the last non-whitespace column.
604 if (EndColNo > SourceLine.size())
605 EndColNo = SourceLine.size();
606 while (EndColNo-1 &&
607 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
608 --EndColNo;
609
610 // If the start/end passed each other, then we are trying to highlight a
611 // range that just exists in whitespace, which must be some sort of other
612 // bug.
613 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
614 }
615
616 // Fill the range with ~'s.
617 for (unsigned i = StartColNo; i < EndColNo; ++i)
618 CaretLine[i] = '~';
619 }
620
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000621 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000622 const char *LineStart,
623 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000624 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000625 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000626 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000627 return FixItInsertionLine;
628
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000629 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
630 I != E; ++I) {
631 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000632 // We have an insertion hint. Determine whether the inserted
633 // code is on the same line as the caret.
634 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000635 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000636 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000637 // Insert the new code into the line just below the code
638 // that the user wrote.
639 unsigned HintColNo
640 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
641 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000642 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000643 if (LastColumnModified > FixItInsertionLine.size())
644 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000645 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000646 FixItInsertionLine.begin() + HintColNo - 1);
647 } else {
648 FixItInsertionLine.clear();
649 break;
650 }
651 }
652 }
653
654 if (FixItInsertionLine.empty())
655 return FixItInsertionLine;
656
657 // Now that we have the entire fixit line, expand the tabs in it.
658 // Since we don't want to insert spaces in the middle of a word,
659 // find each word and the column it should line up with and insert
660 // spaces until they match.
661 unsigned FixItPos = 0;
662 unsigned LinePos = 0;
663 unsigned TabExpandedCol = 0;
664 unsigned LineLength = LineEnd - LineStart;
665
666 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
667 // Find the next word in the FixIt line.
668 while (FixItPos < FixItInsertionLine.size() &&
669 FixItInsertionLine[FixItPos] == ' ')
670 ++FixItPos;
671 unsigned CharDistance = FixItPos - TabExpandedCol;
672
673 // Walk forward in the source line, keeping track of
674 // the tab-expanded column.
675 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
676 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
677 ++TabExpandedCol;
678 else
679 TabExpandedCol =
680 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
681
682 // Adjust the fixit line to match this column.
683 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
684 FixItPos = TabExpandedCol;
685
686 // Walk to the end of the word.
687 while (FixItPos < FixItInsertionLine.size() &&
688 FixItInsertionLine[FixItPos] != ' ')
689 ++FixItPos;
690 }
691
692 return FixItInsertionLine;
693 }
694
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000695 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
696 // Scan the source line, looking for tabs. If we find any, manually expand
697 // them to spaces and update the CaretLine to match.
698 for (unsigned i = 0; i != SourceLine.size(); ++i) {
699 if (SourceLine[i] != '\t') continue;
700
701 // Replace this tab with at least one space.
702 SourceLine[i] = ' ';
703
704 // Compute the number of spaces we need to insert.
705 unsigned TabStop = DiagOpts.TabStop;
706 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
707 "Invalid -ftabstop value");
708 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
709 assert(NumSpaces < TabStop && "Invalid computation of space amt");
710
711 // Insert spaces into the SourceLine.
712 SourceLine.insert(i+1, NumSpaces, ' ');
713
714 // Insert spaces or ~'s into CaretLine.
715 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
716 }
717 }
718
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000719 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000720 if (!DiagOpts.ShowParseableFixits)
721 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000722
Chandler Carruthcca61582011-09-02 06:30:30 +0000723 // We follow FixItRewriter's example in not (yet) handling
724 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000725 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
726 I != E; ++I) {
727 if (I->RemoveRange.isInvalid() ||
728 I->RemoveRange.getBegin().isMacroID() ||
729 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000730 return;
731 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000732
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000733 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
734 I != E; ++I) {
735 SourceLocation BLoc = I->RemoveRange.getBegin();
736 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000737
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000738 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
739 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000740
Chandler Carruthcca61582011-09-02 06:30:30 +0000741 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000742 if (I->RemoveRange.isTokenRange())
743 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000744
Chandler Carruthcca61582011-09-02 06:30:30 +0000745 // We specifically do not do word-wrapping or tab-expansion here,
746 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000747 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000748 if (PLoc.isInvalid())
749 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000750
Chandler Carruthcca61582011-09-02 06:30:30 +0000751 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000752 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000753 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
754 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
755 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
756 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
757 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000758 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000759 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000760 }
761 }
762};
763
764} // end namespace
765
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000766/// \brief Skip over whitespace in the string, starting at the given
767/// index.
768///
769/// \returns The index of the first non-whitespace character that is
770/// greater than or equal to Idx or, if no such character exists,
771/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000772static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000773 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000774 unsigned Length) {
775 while (Idx < Length && isspace(Str[Idx]))
776 ++Idx;
777 return Idx;
778}
779
780/// \brief If the given character is the start of some kind of
781/// balanced punctuation (e.g., quotes or parentheses), return the
782/// character that will terminate the punctuation.
783///
784/// \returns The ending punctuation character, if any, or the NULL
785/// character if the input character does not start any punctuation.
786static inline char findMatchingPunctuation(char c) {
787 switch (c) {
788 case '\'': return '\'';
789 case '`': return '\'';
790 case '"': return '"';
791 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000792 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000793 case '{': return '}';
794 default: break;
795 }
796
797 return 0;
798}
799
800/// \brief Find the end of the word starting at the given offset
801/// within a string.
802///
803/// \returns the index pointing one character past the end of the
804/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000805static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000806 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000807 unsigned Length, unsigned Column,
808 unsigned Columns) {
809 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000810 unsigned End = Start + 1;
811
Daniel Dunbareae18f82009-12-06 09:56:18 +0000812 // If we are already at the end of the string, take that as the word.
813 if (End == Str.size())
814 return End;
815
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000816 // Determine if the start of the string is actually opening
817 // punctuation, e.g., a quote or parentheses.
818 char EndPunct = findMatchingPunctuation(Str[Start]);
819 if (!EndPunct) {
820 // This is a normal word. Just find the first space character.
821 while (End < Length && !isspace(Str[End]))
822 ++End;
823 return End;
824 }
825
826 // We have the start of a balanced punctuation sequence (quotes,
827 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000828 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000829 PunctuationEndStack.push_back(EndPunct);
830 while (End < Length && !PunctuationEndStack.empty()) {
831 if (Str[End] == PunctuationEndStack.back())
832 PunctuationEndStack.pop_back();
833 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
834 PunctuationEndStack.push_back(SubEndPunct);
835
836 ++End;
837 }
838
839 // Find the first space character after the punctuation ended.
840 while (End < Length && !isspace(Str[End]))
841 ++End;
842
843 unsigned PunctWordLength = End - Start;
844 if (// If the word fits on this line
845 Column + PunctWordLength <= Columns ||
846 // ... or the word is "short enough" to take up the next line
847 // without too much ugly white space
848 PunctWordLength < Columns/3)
849 return End; // Take the whole thing as a single "word".
850
851 // The whole quoted/parenthesized string is too long to print as a
852 // single "word". Instead, find the "word" that starts just after
853 // the punctuation and use that end-point instead. This will recurse
854 // until it finds something small enough to consider a word.
855 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
856}
857
858/// \brief Print the given string to a stream, word-wrapping it to
859/// some number of columns in the process.
860///
861/// \brief OS the stream to which the word-wrapping string will be
862/// emitted.
863///
864/// \brief Str the string to word-wrap and output.
865///
866/// \brief Columns the number of columns to word-wrap to.
867///
868/// \brief Column the column number at which the first character of \p
869/// Str will be printed. This will be non-zero when part of the first
870/// line has already been printed.
871///
872/// \brief Indentation the number of spaces to indent any lines beyond
873/// the first line.
874///
875/// \returns true if word-wrapping was required, or false if the
876/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000877static bool PrintWordWrapped(raw_ostream &OS,
878 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000879 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000880 unsigned Column = 0,
881 unsigned Indentation = WordWrapIndentation) {
882 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000883
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000884 // If there is a newline in this message somewhere, find that
885 // newline and split the message into the part before the newline
886 // (which will be word-wrapped) and the part from the newline one
887 // (which will be emitted unchanged).
888 for (unsigned I = 0; I != Length; ++I)
889 if (Str[I] == '\n') {
890 Length = I;
891 break;
892 }
893
894 // The string used to indent each line.
895 llvm::SmallString<16> IndentStr;
896 IndentStr.assign(Indentation, ' ');
897 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000898 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000899 WordStart = WordEnd) {
900 // Find the beginning of the next word.
901 WordStart = skipWhitespace(WordStart, Str, Length);
902 if (WordStart == Length)
903 break;
904
905 // Find the end of this word.
906 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000907
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000908 // Does this word fit on the current line?
909 unsigned WordLength = WordEnd - WordStart;
910 if (Column + WordLength < Columns) {
911 // This word fits on the current line; print it there.
912 if (WordStart) {
913 OS << ' ';
914 Column += 1;
915 }
916 OS.write(&Str[WordStart], WordLength);
917 Column += WordLength;
918 continue;
919 }
920
921 // This word does not fit on the current line, so wrap to the next
922 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000923 OS << '\n';
924 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000925 OS.write(&Str[WordStart], WordLength);
926 Column = Indentation + WordLength;
927 Wrapped = true;
928 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000929
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000930 if (Length == Str.size())
931 return Wrapped; // We're done.
932
933 // There is a newline in the message, followed by something that
934 // will not be word-wrapped. Print that.
935 OS.write(&Str[Length], Str.size() - Length);
936 return true;
937}
Chris Lattner94f55782009-02-17 07:38:37 +0000938
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000939/// Get the presumed location of a diagnostic message. This computes the
940/// presumed location for the top of any macro backtrace when present.
941static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
942 SourceLocation Loc) {
943 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
944 // walk to the top of the macro call stack.
945 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000946 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000947 Loc = getImmediateMacroCallerLoc(SM, Loc);
948 }
949
950 return SM.getPresumedLoc(Loc);
951}
952
Chandler Carruth5770bb72011-09-07 08:05:58 +0000953/// \brief Print out the file/line/column information and include trace.
954///
955/// This method handlen the emission of the diagnostic location information.
956/// This includes extracting as much location information as is present for the
957/// diagnostic and printing it, as well as any include stack or source ranges
958/// necessary.
959void TextDiagnosticPrinter::EmitDiagnosticLoc(Diagnostic::Level Level,
960 const DiagnosticInfo &Info,
961 const SourceManager &SM,
962 PresumedLoc PLoc) {
963 if (PLoc.isInvalid()) {
964 // At least print the file name if available:
965 FileID FID = SM.getFileID(Info.getLocation());
966 if (!FID.isInvalid()) {
967 const FileEntry* FE = SM.getFileEntryForID(FID);
968 if (FE && FE->getName()) {
969 OS << FE->getName();
970 if (FE->getDevice() == 0 && FE->getInode() == 0
971 && FE->getFileMode() == 0) {
972 // in PCH is a guess, but a good one:
973 OS << " (in PCH)";
974 }
975 OS << ": ";
976 }
977 }
978 return;
979 }
980 unsigned LineNo = PLoc.getLine();
981
982 if (!DiagOpts->ShowLocation)
983 return;
984
985 if (DiagOpts->ShowColors)
986 OS.changeColor(savedColor, true);
987
988 OS << PLoc.getFilename();
989 switch (DiagOpts->Format) {
990 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
991 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
992 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
993 }
994
995 if (DiagOpts->ShowColumn)
996 // Compute the column number.
997 if (unsigned ColNo = PLoc.getColumn()) {
998 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
999 OS << ',';
1000 ColNo--;
1001 } else
1002 OS << ':';
1003 OS << ColNo;
1004 }
1005 switch (DiagOpts->Format) {
1006 case DiagnosticOptions::Clang:
1007 case DiagnosticOptions::Vi: OS << ':'; break;
1008 case DiagnosticOptions::Msvc: OS << ") : "; break;
1009 }
1010
1011 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1012 FileID CaretFileID =
1013 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
1014 bool PrintedRange = false;
1015
1016 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1017 // Ignore invalid ranges.
1018 if (!Info.getRange(i).isValid()) continue;
1019
1020 SourceLocation B = Info.getRange(i).getBegin();
1021 SourceLocation E = Info.getRange(i).getEnd();
1022 B = SM.getExpansionLoc(B);
1023 E = SM.getExpansionLoc(E);
1024
1025 // If the End location and the start location are the same and are a
1026 // macro location, then the range was something that came from a
1027 // macro expansion or _Pragma. If this is an object-like macro, the
1028 // best we can do is to highlight the range. If this is a
1029 // function-like macro, we'd also like to highlight the arguments.
1030 if (B == E && Info.getRange(i).getEnd().isMacroID())
1031 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
1032
1033 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1034 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1035
1036 // If the start or end of the range is in another file, just discard
1037 // it.
1038 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1039 continue;
1040
1041 // Add in the length of the token, so that we cover multi-char
1042 // tokens.
1043 unsigned TokSize = 0;
1044 if (Info.getRange(i).isTokenRange())
1045 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1046
1047 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1048 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1049 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1050 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1051 << '}';
1052 PrintedRange = true;
1053 }
1054
1055 if (PrintedRange)
1056 OS << ':';
1057 }
1058 OS << ' ';
1059}
1060
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001061void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +00001062 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +00001063 // Default implementation (Warnings/errors count).
1064 DiagnosticClient::HandleDiagnostic(Level, Info);
1065
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001066 // Keeps track of the the starting position of the location
1067 // information (e.g., "foo.c:10:4:") that precedes the error
1068 // message. We use this information to determine how long the
1069 // file+line+column number prefix is.
1070 uint64_t StartOfLocationInfo = OS.tell();
1071
Daniel Dunbarb96b6702010-02-25 03:23:40 +00001072 if (!Prefix.empty())
1073 OS << Prefix << ": ";
1074
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001075 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001076 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001077 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001078
Chandler Carruth5770bb72011-09-07 08:05:58 +00001079 // First, if this diagnostic is not in the main file, print out the
1080 // "included from" lines.
1081 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1082 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +00001083
Chandler Carruth5770bb72011-09-07 08:05:58 +00001084 // Next emit the location of this particular diagnostic.
1085 EmitDiagnosticLoc(Level, Info, SM, PLoc);
Axel Naumann04331162011-01-27 10:55:51 +00001086
Chandler Carruth5770bb72011-09-07 08:05:58 +00001087 if (DiagOpts->ShowColors)
1088 OS.resetColor();
Torok Edwin603fca72009-06-04 07:18:23 +00001089 }
1090
Daniel Dunbareace8742009-11-04 06:24:30 +00001091 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001092 // Print diagnostic category in bold and color
1093 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001094 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Torok Edwin603fca72009-06-04 07:18:23 +00001095 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1096 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1097 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1098 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001099 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001100 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001101
Reid Spencer5f016e22007-07-11 17:01:13 +00001102 switch (Level) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001103 case Diagnostic::Ignored: llvm_unreachable("Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001104 case Diagnostic::Note: OS << "note: "; break;
1105 case Diagnostic::Warning: OS << "warning: "; break;
1106 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001107 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001108 }
Torok Edwin603fca72009-06-04 07:18:23 +00001109
Daniel Dunbareace8742009-11-04 06:24:30 +00001110 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001111 OS.resetColor();
1112
Chris Lattnerf4c83962008-11-19 06:51:40 +00001113 llvm::SmallString<100> OutStr;
1114 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001115
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001116 if (DiagOpts->ShowNames &&
1117 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1118 OutStr += " [";
1119 OutStr += DiagnosticIDs::getName(Info.getID());
1120 OutStr += "]";
1121 }
1122
Chris Lattnerc9b88902010-05-04 21:13:21 +00001123 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001124 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001125 // Was this a warning mapped to an error using -Werror or pragma?
1126 if (Level == Diagnostic::Error &&
1127 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1128 diag::Mapping mapping = diag::MAP_IGNORE;
1129 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1130 &mapping);
1131 if (mapping == diag::MAP_WARNING)
1132 OptionName += "-Werror";
1133 }
1134
Chris Lattner5f9e2722011-07-23 10:55:15 +00001135 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001136 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001137 if (!OptionName.empty())
1138 OptionName += ',';
1139 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001140 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001141 } else if (Info.getID() == diag::fatal_too_many_errors) {
1142 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001143 } else {
1144 // If the diagnostic is an extension diagnostic and not enabled by default
1145 // then it must have been turned on with -pedantic.
1146 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001147 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1148 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001149 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001150 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001151 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001152 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001153
1154 // If the user wants to see category information, include it too.
1155 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001156 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001157 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001158
Chris Lattnerc9b88902010-05-04 21:13:21 +00001159 // If there is any categorization information, include it.
1160 if (!OptionName.empty() || DiagCategory != 0) {
1161 bool NeedsComma = false;
1162 OutStr += " [";
1163
1164 if (!OptionName.empty()) {
1165 OutStr += OptionName;
1166 NeedsComma = true;
1167 }
1168
1169 if (DiagCategory) {
1170 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001171 if (DiagOpts->ShowCategories == 1)
1172 OutStr += llvm::utostr(DiagCategory);
1173 else {
1174 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001175 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001176 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001177 }
1178
1179 OutStr += "]";
1180 }
1181
1182
Daniel Dunbareace8742009-11-04 06:24:30 +00001183 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001184 // Print warnings, errors and fatal errors in bold, no color
1185 switch (Level) {
1186 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1187 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1188 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1189 default: break; //don't bold notes
1190 }
1191 }
1192
Daniel Dunbareace8742009-11-04 06:24:30 +00001193 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001194 // We will be word-wrapping the error message, so compute the
1195 // column number where we currently are (after printing the
1196 // location information).
1197 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001198 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001199 } else {
1200 OS.write(OutStr.begin(), OutStr.size());
1201 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001202 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001203 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001204 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001205
Douglas Gregordf667e72009-03-10 20:44:00 +00001206 // If caret diagnostics are enabled and we have location, we want to
1207 // emit the caret. However, we only do this if the location moved
1208 // from the last diagnostic, if the last diagnostic was a note that
1209 // was part of a different warning or error diagnostic, or if the
1210 // diagnostic has ranges. We don't want to emit the same caret
1211 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001212 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001213 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001214 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001215 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001216 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001217 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001218 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001219
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001220 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001221 SmallVector<CharSourceRange, 20> Ranges;
1222 Ranges.reserve(Info.getNumRanges());
1223 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1224 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001225
Chandler Carruth5182a182011-09-07 01:47:09 +00001226 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001227 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001228 if (Hint.RemoveRange.isValid())
1229 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001230 }
1231
Chandler Carruth026cb762011-09-25 23:01:05 +00001232 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1233 assert(DiagOpts && "Unexpected diagnostic without options set");
1234
1235 TextDiagnostic TextDiag(*this, OS, Info.getSourceManager(),
1236 *LangOpts, *DiagOpts);
1237 unsigned MacroDepth = 0;
1238 TextDiag.Emit(LastLoc, Ranges, llvm::makeArrayRef(Info.getFixItHints(),
1239 Info.getNumFixItHints()),
1240 MacroDepth);
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001242
Chris Lattnera03a5b52008-11-19 06:56:25 +00001243 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001244}