blob: 26c50ce5cc5aaf764f2b5125c681a3d77d7293fd [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
Reid Spencer5f016e22007-07-11 17:01:13 +0000104/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
105/// any characters in LineNo that intersect the SourceRange.
Chris Lattner0a76aae2010-06-18 22:45:06 +0000106void TextDiagnosticPrinter::HighlightRange(const CharSourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000107 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +0000108 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +0000109 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +0000110 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000111 assert(CaretLine.size() == SourceLine.size() &&
112 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 if (!R.isValid()) return;
114
Chandler Carruth40278532011-07-25 16:49:02 +0000115 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
116 SourceLocation End = SM.getExpansionLoc(R.getEnd());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000117
Chris Lattner34837a52009-02-17 05:19:10 +0000118 // If the End location and the start location are the same and are a macro
119 // location, then the range was something that came from a macro expansion
120 // or _Pragma. If this is an object-like macro, the best we can do is to
121 // highlight the range. If this is a function-like macro, we'd also like to
122 // highlight the arguments.
123 if (Begin == End && R.getEnd().isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000124 End = SM.getExpansionRange(R.getEnd()).second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000125
Chandler Carruth64211622011-07-25 21:09:52 +0000126 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000127 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +0000128 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000129
Chandler Carruth64211622011-07-25 21:09:52 +0000130 unsigned EndLineNo = SM.getExpansionLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000131 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +0000132 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000133
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 // Compute the column number of the start.
135 unsigned StartColNo = 0;
136 if (StartLineNo == LineNo) {
Chandler Carrutha77c0312011-07-25 20:57:57 +0000137 StartColNo = SM.getExpansionColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (StartColNo) --StartColNo; // Zero base the col #.
139 }
140
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +0000142 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 if (EndLineNo == LineNo) {
Chandler Carrutha77c0312011-07-25 20:57:57 +0000144 EndColNo = SM.getExpansionColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 if (EndColNo) {
146 --EndColNo; // Zero base the col #.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000147
Chris Lattner0a76aae2010-06-18 22:45:06 +0000148 // Add in the length of the token, so that we cover multi-char tokens if
149 // this is a token range.
150 if (R.isTokenRange())
151 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000153 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 }
155 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000156
Chris Lattner41e79e22010-02-12 18:52:52 +0000157 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000158
Tom Care45f9b7e2010-06-21 21:21:01 +0000159 // Check that a token range does not highlight only whitespace.
160 if (R.isTokenRange()) {
161 // Pick the first non-whitespace column.
162 while (StartColNo < SourceLine.size() &&
163 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
164 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000165
Tom Care45f9b7e2010-06-21 21:21:01 +0000166 // Pick the last non-whitespace column.
167 if (EndColNo > SourceLine.size())
168 EndColNo = SourceLine.size();
169 while (EndColNo-1 &&
170 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
171 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000172
Axel Naumann04331162011-01-27 10:55:51 +0000173 // If the start/end passed each other, then we are trying to highlight a
174 // range that just exists in whitespace, which must be some sort of other
175 // bug.
Tom Care45f9b7e2010-06-21 21:21:01 +0000176 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
177 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000180 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000181 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000182}
183
Douglas Gregor47f71772009-05-01 23:32:58 +0000184/// \brief When the source code line we want to print is too long for
185/// the terminal, select the "interesting" region.
186static void SelectInterestingSourceRegion(std::string &SourceLine,
187 std::string &CaretLine,
188 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000189 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000190 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000191 unsigned MaxSize = std::max(SourceLine.size(),
192 std::max(CaretLine.size(),
193 FixItInsertionLine.size()));
194 if (MaxSize > SourceLine.size())
195 SourceLine.resize(MaxSize, ' ');
196 if (MaxSize > CaretLine.size())
197 CaretLine.resize(MaxSize, ' ');
198 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
199 FixItInsertionLine.resize(MaxSize, ' ');
200
Douglas Gregor47f71772009-05-01 23:32:58 +0000201 // Find the slice that we need to display the full caret line
202 // correctly.
203 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
204 for (; CaretStart != CaretEnd; ++CaretStart)
205 if (!isspace(CaretLine[CaretStart]))
206 break;
207
208 for (; CaretEnd != CaretStart; --CaretEnd)
209 if (!isspace(CaretLine[CaretEnd - 1]))
210 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000211
212 // Make sure we don't chop the string shorter than the caret token
213 // itself.
214 if (CaretEnd < EndOfCaretToken)
215 CaretEnd = EndOfCaretToken;
216
Douglas Gregor844da342009-05-03 04:33:32 +0000217 // If we have a fix-it line, make sure the slice includes all of the
218 // fix-it information.
219 if (!FixItInsertionLine.empty()) {
220 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
221 for (; FixItStart != FixItEnd; ++FixItStart)
222 if (!isspace(FixItInsertionLine[FixItStart]))
223 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000224
Douglas Gregor844da342009-05-03 04:33:32 +0000225 for (; FixItEnd != FixItStart; --FixItEnd)
226 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
227 break;
228
229 if (FixItStart < CaretStart)
230 CaretStart = FixItStart;
231 if (FixItEnd > CaretEnd)
232 CaretEnd = FixItEnd;
233 }
234
Douglas Gregor47f71772009-05-01 23:32:58 +0000235 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
236 // parts of the caret line. While this slice is smaller than the
237 // number of columns we have, try to grow the slice to encompass
238 // more context.
239
240 // If the end of the interesting region comes before we run out of
241 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000242 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000243 CaretStart = 0;
244
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000245 unsigned TargetColumns = Columns;
246 if (TargetColumns > 8)
247 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000248 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000249 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000250 bool ExpandedRegion = false;
251 // Move the start of the interesting region left until we've
252 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000253 if (CaretStart == 1)
254 CaretStart = 0;
255 else if (CaretStart > 1) {
256 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000257
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000258 // Skip over any whitespace we see here; we're looking for
259 // another bit of interesting text.
260 while (NewStart && isspace(SourceLine[NewStart]))
261 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000262
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000263 // Skip over this bit of "interesting" text.
264 while (NewStart && !isspace(SourceLine[NewStart]))
265 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000266
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000267 // Move up to the non-whitespace character we just saw.
268 if (NewStart)
269 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000270
271 // If we're still within our limit, update the starting
272 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000273 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000274 CaretStart = NewStart;
275 ExpandedRegion = true;
276 }
277 }
278
279 // Move the end of the interesting region right until we've
280 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000281 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000282 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000283 unsigned NewEnd = CaretEnd;
284
285 // Skip over any whitespace we see here; we're looking for
286 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000287 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000288 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000289
Douglas Gregor47f71772009-05-01 23:32:58 +0000290 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000291 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000292 ++NewEnd;
293
294 if (NewEnd - CaretStart <= TargetColumns) {
295 CaretEnd = NewEnd;
296 ExpandedRegion = true;
297 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000298 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000299
300 if (!ExpandedRegion)
301 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000302 }
303
304 // [CaretStart, CaretEnd) is the slice we want. Update the various
305 // output lines to show only this slice, with two-space padding
306 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000307 if (CaretEnd < SourceLine.size())
308 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000309 if (CaretEnd < CaretLine.size())
310 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000311 if (FixItInsertionLine.size() > CaretEnd)
312 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000313
Douglas Gregor47f71772009-05-01 23:32:58 +0000314 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000315 SourceLine.replace(0, CaretStart, " ...");
316 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000317 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000318 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000319 }
320}
321
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000322/// Look through spelling locations for a macro argument expansion, and
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000323/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000324/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000325/// don't skip anything and return the starting location.
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000326static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000327 SourceLocation StartLoc) {
328 for (SourceLocation L = StartLoc; L.isMacroID();
329 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruth96d35892011-07-26 03:03:00 +0000330 if (SM.isMacroArgExpansion(L))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000331 return L;
332 }
333
334 // Otherwise just return initial location, there's nothing to skip.
335 return StartLoc;
336}
337
338/// Gets the location of the immediate macro caller, one level up the stack
339/// toward the initial macro typed into the source.
340static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
341 SourceLocation Loc) {
342 if (!Loc.isMacroID()) return Loc;
343
344 // When we have the location of (part of) an expanded parameter, its spelling
345 // location points to the argument as typed into the macro call, and
346 // therefore is used to locate the macro caller.
Chandler Carruth96d35892011-07-26 03:03:00 +0000347 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000348 return SM.getImmediateSpellingLoc(Loc);
349
350 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000351 // expanded (while the spelling is part of the macro definition).
Chandler Carruth999f7392011-07-25 20:52:21 +0000352 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000353}
354
355/// Gets the location of the immediate macro callee, one level down the stack
356/// toward the leaf macro.
357static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
358 SourceLocation Loc) {
359 if (!Loc.isMacroID()) return Loc;
360
361 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000362 // expansion location points to the unexpanded paramater reference within
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000363 // the macro definition (or callee).
Chandler Carruth96d35892011-07-26 03:03:00 +0000364 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth999f7392011-07-25 20:52:21 +0000365 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000366
367 // Otherwise, the callee of the macro is located where this location was
368 // spelled inside the macro definition.
369 return SM.getImmediateSpellingLoc(Loc);
370}
371
Chandler Carruth50c909b2011-08-31 23:59:23 +0000372namespace {
373
374/// \brief Class to encapsulate the logic for printing a caret diagnostic
375/// message.
376///
377/// This class provides an interface for building and emitting a caret
378/// diagnostic, including all of the macro backtrace caret diagnostics, FixIt
379/// Hints, and code snippets. In the presence of macros this turns into
380/// a recursive process and so the class provides common state across the
381/// emission of a particular diagnostic, while each invocation of \see Emit()
382/// walks down the macro stack.
383///
384/// This logic assumes that the core diagnostic location and text has already
385/// been emitted and focuses on emitting the pretty caret display and macro
386/// backtrace following that.
387///
388/// FIXME: Hoist helper routines specific to caret diagnostics into class
389/// methods to reduce paramater passing churn.
390class CaretDiagnostic {
391 TextDiagnosticPrinter &Printer;
392 raw_ostream &OS;
393 const SourceManager &SM;
394 const LangOptions &LangOpts;
395 const DiagnosticOptions &DiagOpts;
396 const unsigned Columns, MacroSkipStart, MacroSkipEnd;
397
398public:
399 CaretDiagnostic(TextDiagnosticPrinter &Printer,
400 raw_ostream &OS,
401 const SourceManager &SM,
402 const LangOptions &LangOpts,
403 const DiagnosticOptions &DiagOpts,
404 unsigned Columns,
405 unsigned MacroSkipStart,
406 unsigned MacroSkipEnd)
407 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts),
408 Columns(Columns), MacroSkipStart(MacroSkipStart),
409 MacroSkipEnd(MacroSkipEnd) {
410 }
411
412 /// \brief Emit the caret diagnostic text.
413 ///
414 /// Walks up the macro expansion stack printing the code snippet, caret,
415 /// underlines and FixItHint display as appropriate at each level. Walk is
416 /// accomplished by calling itself recursively.
417 ///
418 /// FIXME: Switch parameters to ArrayRefs.
419 /// FIXME: Break up massive function into logical units.
420 ///
421 /// \param Loc The location for this caret.
422 /// \param Ranges The underlined ranges for this code snippet.
423 /// \param NumRanges The number of unlined ranges.
424 /// \param Hints The FixIt hints active for this diagnostic.
425 /// \param NumHints The number of hints active for this diagnostic.
426 /// \param OnMacroInst The current depth of the macro expansion stack.
427 void Emit(SourceLocation Loc,
428 CharSourceRange *Ranges,
429 unsigned NumRanges,
430 const FixItHint *Hints,
431 unsigned NumHints,
432 unsigned OnMacroInst = 0) {
433 assert(!Loc.isInvalid() && "must have a valid source location here");
434
435 // If this is a macro ID, first emit information about where this was
436 // expanded (recursively) then emit information about where the token was
437 // spelled from.
438 if (!Loc.isFileID()) {
439 // Whether to suppress printing this macro expansion.
440 bool Suppressed
441 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
442
443 // When processing macros, skip over the expansions leading up to
444 // a macro argument, and trace the argument's expansion stack instead.
445 Loc = skipToMacroArgExpansion(SM, Loc);
446
447 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
448
449 // FIXME: Map ranges?
450 Emit(OneLevelUp, Ranges, NumRanges, Hints, NumHints, OnMacroInst + 1);
451
452 // Map the location.
453 Loc = getImmediateMacroCalleeLoc(SM, Loc);
454
455 // Map the ranges.
456 for (unsigned i = 0; i != NumRanges; ++i) {
457 CharSourceRange &R = Ranges[i];
458 SourceLocation S = R.getBegin(), E = R.getEnd();
459 if (S.isMacroID())
460 R.setBegin(getImmediateMacroCalleeLoc(SM, S));
461 if (E.isMacroID())
462 R.setEnd(getImmediateMacroCalleeLoc(SM, E));
463 }
464
465 if (!Suppressed) {
466 // Don't print recursive expansion notes from an expansion note.
467 Loc = SM.getSpellingLoc(Loc);
468
469 // Get the pretty name, according to #line directives etc.
470 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
471 if (PLoc.isInvalid())
472 return;
473
474 // If this diagnostic is not in the main file, print out the
475 // "included from" lines.
476 Printer.PrintIncludeStack(Diagnostic::Note, PLoc.getIncludeLoc(), SM);
477
478 if (DiagOpts.ShowLocation) {
479 // Emit the file/line/column that this expansion came from.
480 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
481 if (DiagOpts.ShowColumn)
482 OS << PLoc.getColumn() << ':';
483 OS << ' ';
484 }
485 OS << "note: expanded from:\n";
486
487 Emit(Loc, Ranges, NumRanges, 0, 0, OnMacroInst + 1);
488 return;
489 }
490
491 if (OnMacroInst == MacroSkipStart) {
492 // Tell the user that we've skipped contexts.
493 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
494 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
495 "all)\n";
496 }
497
498 return;
499 }
500
501 // Decompose the location into a FID/Offset pair.
502 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
503 FileID FID = LocInfo.first;
504 unsigned FileOffset = LocInfo.second;
505
506 // Get information about the buffer it points into.
507 bool Invalid = false;
508 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
509 if (Invalid)
510 return;
511
512 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
513 unsigned CaretEndColNo
514 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
515
516 // Rewind from the current position to the start of the line.
517 const char *TokPtr = BufStart+FileOffset;
518 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
519
520
521 // Compute the line end. Scan forward from the error position to the end of
522 // the line.
523 const char *LineEnd = TokPtr;
524 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
525 ++LineEnd;
526
527 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
528 // the source line length as currently being computed. See
529 // test/Misc/message-length.c.
530 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
531
532 // Copy the line of code into an std::string for ease of manipulation.
533 std::string SourceLine(LineStart, LineEnd);
534
535 // Create a line for the caret that is filled with spaces that is the same
536 // length as the line of source code.
537 std::string CaretLine(LineEnd-LineStart, ' ');
538
539 // Highlight all of the characters covered by Ranges with ~ characters.
540 if (NumRanges) {
541 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
542
543 for (unsigned i = 0, e = NumRanges; i != e; ++i)
544 Printer.HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine,
545 SourceLine);
546 }
547
548 // Next, insert the caret itself.
549 if (ColNo-1 < CaretLine.size())
550 CaretLine[ColNo-1] = '^';
551 else
552 CaretLine.push_back('^');
553
554 // Scan the source line, looking for tabs. If we find any, manually expand
555 // them to spaces and update the CaretLine to match.
556 for (unsigned i = 0; i != SourceLine.size(); ++i) {
557 if (SourceLine[i] != '\t') continue;
558
559 // Replace this tab with at least one space.
560 SourceLine[i] = ' ';
561
562 // Compute the number of spaces we need to insert.
563 unsigned TabStop = DiagOpts.TabStop;
564 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
565 "Invalid -ftabstop value");
566 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
567 assert(NumSpaces < TabStop && "Invalid computation of space amt");
568
569 // Insert spaces into the SourceLine.
570 SourceLine.insert(i+1, NumSpaces, ' ');
571
572 // Insert spaces or ~'s into CaretLine.
573 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
574 }
575
576 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
577 // to produce easily machine parsable output. Add a space before the
578 // source line and the caret to make it trivial to tell the main diagnostic
579 // line from what the user is intended to see.
580 if (DiagOpts.ShowSourceRanges) {
581 SourceLine = ' ' + SourceLine;
582 CaretLine = ' ' + CaretLine;
583 }
584
Chandler Carruth682630c2011-09-06 22:01:04 +0000585 std::string FixItInsertionLine = BuildFixItInsertionLine(FID, FileOffset,
586 LineStart, LineEnd,
587 Hints, NumHints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000588
589 // If the source line is too long for our terminal, select only the
590 // "interesting" source region within that line.
591 if (Columns && SourceLine.size() > Columns)
592 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
593 CaretEndColNo, Columns);
594
595 // Finally, remove any blank spaces from the end of CaretLine.
596 while (CaretLine[CaretLine.size()-1] == ' ')
597 CaretLine.erase(CaretLine.end()-1);
598
599 // Emit what we have computed.
600 OS << SourceLine << '\n';
601
602 if (DiagOpts.ShowColors)
603 OS.changeColor(caretColor, true);
604 OS << CaretLine << '\n';
605 if (DiagOpts.ShowColors)
606 OS.resetColor();
607
608 if (!FixItInsertionLine.empty()) {
609 if (DiagOpts.ShowColors)
610 // Print fixit line in color
611 OS.changeColor(fixitColor, false);
612 if (DiagOpts.ShowSourceRanges)
613 OS << ' ';
614 OS << FixItInsertionLine << '\n';
615 if (DiagOpts.ShowColors)
616 OS.resetColor();
617 }
618
Chandler Carruthcca61582011-09-02 06:30:30 +0000619 // Print out any parseable fixit information requested by the options.
620 EmitParseableFixits(Hints, NumHints);
621 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000622
Chandler Carruthcca61582011-09-02 06:30:30 +0000623private:
Chandler Carruth682630c2011-09-06 22:01:04 +0000624 std::string BuildFixItInsertionLine(FileID FID, unsigned FileOffset,
625 const char *LineStart,
626 const char *LineEnd,
627 const FixItHint *Hints,
628 unsigned NumHints) {
629 std::string FixItInsertionLine;
630 if (!NumHints || !DiagOpts.ShowFixits)
631 return FixItInsertionLine;
632
633 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
634 Hint != LastHint; ++Hint) {
635 if (!Hint->CodeToInsert.empty()) {
636 // We have an insertion hint. Determine whether the inserted
637 // code is on the same line as the caret.
638 std::pair<FileID, unsigned> HintLocInfo
639 = SM.getDecomposedExpansionLoc(Hint->RemoveRange.getBegin());
640 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
641 SM.getLineNumber(FID, FileOffset)) {
642 // Insert the new code into the line just below the code
643 // that the user wrote.
644 unsigned HintColNo
645 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
646 unsigned LastColumnModified
647 = HintColNo - 1 + Hint->CodeToInsert.size();
648 if (LastColumnModified > FixItInsertionLine.size())
649 FixItInsertionLine.resize(LastColumnModified, ' ');
650 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
651 FixItInsertionLine.begin() + HintColNo - 1);
652 } else {
653 FixItInsertionLine.clear();
654 break;
655 }
656 }
657 }
658
659 if (FixItInsertionLine.empty())
660 return FixItInsertionLine;
661
662 // Now that we have the entire fixit line, expand the tabs in it.
663 // Since we don't want to insert spaces in the middle of a word,
664 // find each word and the column it should line up with and insert
665 // spaces until they match.
666 unsigned FixItPos = 0;
667 unsigned LinePos = 0;
668 unsigned TabExpandedCol = 0;
669 unsigned LineLength = LineEnd - LineStart;
670
671 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
672 // Find the next word in the FixIt line.
673 while (FixItPos < FixItInsertionLine.size() &&
674 FixItInsertionLine[FixItPos] == ' ')
675 ++FixItPos;
676 unsigned CharDistance = FixItPos - TabExpandedCol;
677
678 // Walk forward in the source line, keeping track of
679 // the tab-expanded column.
680 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
681 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
682 ++TabExpandedCol;
683 else
684 TabExpandedCol =
685 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
686
687 // Adjust the fixit line to match this column.
688 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
689 FixItPos = TabExpandedCol;
690
691 // Walk to the end of the word.
692 while (FixItPos < FixItInsertionLine.size() &&
693 FixItInsertionLine[FixItPos] != ' ')
694 ++FixItPos;
695 }
696
697 return FixItInsertionLine;
698 }
699
Chandler Carruthcca61582011-09-02 06:30:30 +0000700 void EmitParseableFixits(const FixItHint *Hints, unsigned NumHints) {
701 if (!DiagOpts.ShowParseableFixits)
702 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000703
Chandler Carruthcca61582011-09-02 06:30:30 +0000704 // We follow FixItRewriter's example in not (yet) handling
705 // fix-its in macros.
706 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
707 if (Hint->RemoveRange.isInvalid() ||
708 Hint->RemoveRange.getBegin().isMacroID() ||
709 Hint->RemoveRange.getEnd().isMacroID())
710 return;
711 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000712
Chandler Carruthcca61582011-09-02 06:30:30 +0000713 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
714 SourceLocation B = Hint->RemoveRange.getBegin();
715 SourceLocation E = Hint->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000716
Chandler Carruthcca61582011-09-02 06:30:30 +0000717 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
718 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000719
Chandler Carruthcca61582011-09-02 06:30:30 +0000720 // Adjust for token ranges.
721 if (Hint->RemoveRange.isTokenRange())
722 EInfo.second += Lexer::MeasureTokenLength(E, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000723
Chandler Carruthcca61582011-09-02 06:30:30 +0000724 // We specifically do not do word-wrapping or tab-expansion here,
725 // because this is supposed to be easy to parse.
726 PresumedLoc PLoc = SM.getPresumedLoc(B);
727 if (PLoc.isInvalid())
728 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000729
Chandler Carruthcca61582011-09-02 06:30:30 +0000730 OS << "fix-it:\"";
731 OS.write_escaped(SM.getPresumedLoc(B).getFilename());
732 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
733 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
734 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
735 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
736 << "}:\"";
737 OS.write_escaped(Hint->CodeToInsert);
738 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000739 }
740 }
741};
742
743} // end namespace
744
Chris Lattner83068312011-06-28 05:11:33 +0000745void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000746 CharSourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000747 unsigned NumRanges,
Chris Lattner5c5db4e2010-04-20 20:49:23 +0000748 const SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000749 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000750 unsigned NumHints,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000751 unsigned Columns,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000752 unsigned MacroSkipStart,
753 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000754 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chandler Carruth50c909b2011-08-31 23:59:23 +0000755 assert(DiagOpts && "Unexpected diagnostic without options set");
756 // FIXME: Remove this method and have clients directly build and call Emit on
757 // the CaretDiagnostic object.
758 CaretDiagnostic CaretDiag(*this, OS, SM, *LangOpts, *DiagOpts,
759 Columns, MacroSkipStart, MacroSkipEnd);
760 CaretDiag.Emit(Loc, Ranges, NumRanges, Hints, NumHints);
Chris Lattner94f55782009-02-17 07:38:37 +0000761}
762
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000763/// \brief Skip over whitespace in the string, starting at the given
764/// index.
765///
766/// \returns The index of the first non-whitespace character that is
767/// greater than or equal to Idx or, if no such character exists,
768/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000769static unsigned skipWhitespace(unsigned Idx,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000770 const SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000771 unsigned Length) {
772 while (Idx < Length && isspace(Str[Idx]))
773 ++Idx;
774 return Idx;
775}
776
777/// \brief If the given character is the start of some kind of
778/// balanced punctuation (e.g., quotes or parentheses), return the
779/// character that will terminate the punctuation.
780///
781/// \returns The ending punctuation character, if any, or the NULL
782/// character if the input character does not start any punctuation.
783static inline char findMatchingPunctuation(char c) {
784 switch (c) {
785 case '\'': return '\'';
786 case '`': return '\'';
787 case '"': return '"';
788 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000789 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000790 case '{': return '}';
791 default: break;
792 }
793
794 return 0;
795}
796
797/// \brief Find the end of the word starting at the given offset
798/// within a string.
799///
800/// \returns the index pointing one character past the end of the
801/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000802static unsigned findEndOfWord(unsigned Start,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000803 const SmallVectorImpl<char> &Str,
Daniel Dunbareae18f82009-12-06 09:56:18 +0000804 unsigned Length, unsigned Column,
805 unsigned Columns) {
806 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000807 unsigned End = Start + 1;
808
Daniel Dunbareae18f82009-12-06 09:56:18 +0000809 // If we are already at the end of the string, take that as the word.
810 if (End == Str.size())
811 return End;
812
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000813 // Determine if the start of the string is actually opening
814 // punctuation, e.g., a quote or parentheses.
815 char EndPunct = findMatchingPunctuation(Str[Start]);
816 if (!EndPunct) {
817 // This is a normal word. Just find the first space character.
818 while (End < Length && !isspace(Str[End]))
819 ++End;
820 return End;
821 }
822
823 // We have the start of a balanced punctuation sequence (quotes,
824 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000825 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000826 PunctuationEndStack.push_back(EndPunct);
827 while (End < Length && !PunctuationEndStack.empty()) {
828 if (Str[End] == PunctuationEndStack.back())
829 PunctuationEndStack.pop_back();
830 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
831 PunctuationEndStack.push_back(SubEndPunct);
832
833 ++End;
834 }
835
836 // Find the first space character after the punctuation ended.
837 while (End < Length && !isspace(Str[End]))
838 ++End;
839
840 unsigned PunctWordLength = End - Start;
841 if (// If the word fits on this line
842 Column + PunctWordLength <= Columns ||
843 // ... or the word is "short enough" to take up the next line
844 // without too much ugly white space
845 PunctWordLength < Columns/3)
846 return End; // Take the whole thing as a single "word".
847
848 // The whole quoted/parenthesized string is too long to print as a
849 // single "word". Instead, find the "word" that starts just after
850 // the punctuation and use that end-point instead. This will recurse
851 // until it finds something small enough to consider a word.
852 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
853}
854
855/// \brief Print the given string to a stream, word-wrapping it to
856/// some number of columns in the process.
857///
858/// \brief OS the stream to which the word-wrapping string will be
859/// emitted.
860///
861/// \brief Str the string to word-wrap and output.
862///
863/// \brief Columns the number of columns to word-wrap to.
864///
865/// \brief Column the column number at which the first character of \p
866/// Str will be printed. This will be non-zero when part of the first
867/// line has already been printed.
868///
869/// \brief Indentation the number of spaces to indent any lines beyond
870/// the first line.
871///
872/// \returns true if word-wrapping was required, or false if the
873/// string fit on the first line.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000874static bool PrintWordWrapped(raw_ostream &OS,
875 const SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000876 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000877 unsigned Column = 0,
878 unsigned Indentation = WordWrapIndentation) {
879 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000880
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000881 // If there is a newline in this message somewhere, find that
882 // newline and split the message into the part before the newline
883 // (which will be word-wrapped) and the part from the newline one
884 // (which will be emitted unchanged).
885 for (unsigned I = 0; I != Length; ++I)
886 if (Str[I] == '\n') {
887 Length = I;
888 break;
889 }
890
891 // The string used to indent each line.
892 llvm::SmallString<16> IndentStr;
893 IndentStr.assign(Indentation, ' ');
894 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000895 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000896 WordStart = WordEnd) {
897 // Find the beginning of the next word.
898 WordStart = skipWhitespace(WordStart, Str, Length);
899 if (WordStart == Length)
900 break;
901
902 // Find the end of this word.
903 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000904
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000905 // Does this word fit on the current line?
906 unsigned WordLength = WordEnd - WordStart;
907 if (Column + WordLength < Columns) {
908 // This word fits on the current line; print it there.
909 if (WordStart) {
910 OS << ' ';
911 Column += 1;
912 }
913 OS.write(&Str[WordStart], WordLength);
914 Column += WordLength;
915 continue;
916 }
917
918 // This word does not fit on the current line, so wrap to the next
919 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000920 OS << '\n';
921 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000922 OS.write(&Str[WordStart], WordLength);
923 Column = Indentation + WordLength;
924 Wrapped = true;
925 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000926
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000927 if (Length == Str.size())
928 return Wrapped; // We're done.
929
930 // There is a newline in the message, followed by something that
931 // will not be word-wrapped. Print that.
932 OS.write(&Str[Length], Str.size() - Length);
933 return true;
934}
Chris Lattner94f55782009-02-17 07:38:37 +0000935
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000936/// Get the presumed location of a diagnostic message. This computes the
937/// presumed location for the top of any macro backtrace when present.
938static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
939 SourceLocation Loc) {
940 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
941 // walk to the top of the macro call stack.
942 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000943 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000944 Loc = getImmediateMacroCallerLoc(SM, Loc);
945 }
946
947 return SM.getPresumedLoc(Loc);
948}
949
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000950void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000951 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000952 // Default implementation (Warnings/errors count).
953 DiagnosticClient::HandleDiagnostic(Level, Info);
954
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000955 // Keeps track of the the starting position of the location
956 // information (e.g., "foo.c:10:4:") that precedes the error
957 // message. We use this information to determine how long the
958 // file+line+column number prefix is.
959 uint64_t StartOfLocationInfo = OS.tell();
960
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000961 if (!Prefix.empty())
962 OS << Prefix << ": ";
963
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000964 // If the location is specified, print out a file/line/col and include trace
965 // if enabled.
966 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000967 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000968 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
Axel Naumann04331162011-01-27 10:55:51 +0000969 if (PLoc.isInvalid()) {
970 // At least print the file name if available:
971 FileID FID = SM.getFileID(Info.getLocation());
972 if (!FID.isInvalid()) {
973 const FileEntry* FE = SM.getFileEntryForID(FID);
974 if (FE && FE->getName()) {
975 OS << FE->getName();
976 if (FE->getDevice() == 0 && FE->getInode() == 0
977 && FE->getFileMode() == 0) {
978 // in PCH is a guess, but a good one:
979 OS << " (in PCH)";
980 }
981 OS << ": ";
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000982 }
Axel Naumann04331162011-01-27 10:55:51 +0000983 }
984 } else {
985 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000986
Axel Naumann04331162011-01-27 10:55:51 +0000987 // First, if this diagnostic is not in the main file, print out the
988 // "included from" lines.
Chandler Carruth0d6b8932011-08-31 23:59:19 +0000989 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
990 StartOfLocationInfo = OS.tell();
Axel Naumann04331162011-01-27 10:55:51 +0000991
992 // Compute the column number.
Matt Beaumont-Gay32ad9352011-03-31 01:46:47 +0000993 if (DiagOpts->ShowLocation) {
Axel Naumann04331162011-01-27 10:55:51 +0000994 if (DiagOpts->ShowColors)
995 OS.changeColor(savedColor, true);
996
Douglas Gregorc9471b02011-05-21 17:07:29 +0000997 OS << PLoc.getFilename();
998 switch (DiagOpts->Format) {
999 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
1000 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
1001 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
Axel Naumann04331162011-01-27 10:55:51 +00001002 }
Douglas Gregorc9471b02011-05-21 17:07:29 +00001003 if (DiagOpts->ShowColumn)
1004 if (unsigned ColNo = PLoc.getColumn()) {
1005 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
1006 OS << ',';
1007 ColNo--;
1008 } else
1009 OS << ':';
1010 OS << ColNo;
1011 }
1012 switch (DiagOpts->Format) {
1013 case DiagnosticOptions::Clang:
1014 case DiagnosticOptions::Vi: OS << ':'; break;
1015 case DiagnosticOptions::Msvc: OS << ") : "; break;
1016 }
1017
1018
Axel Naumann04331162011-01-27 10:55:51 +00001019 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
1020 FileID CaretFileID =
Chandler Carruth40278532011-07-25 16:49:02 +00001021 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
Axel Naumann04331162011-01-27 10:55:51 +00001022 bool PrintedRange = false;
1023
1024 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
1025 // Ignore invalid ranges.
1026 if (!Info.getRange(i).isValid()) continue;
1027
1028 SourceLocation B = Info.getRange(i).getBegin();
1029 SourceLocation E = Info.getRange(i).getEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00001030 B = SM.getExpansionLoc(B);
1031 E = SM.getExpansionLoc(E);
Axel Naumann04331162011-01-27 10:55:51 +00001032
1033 // If the End location and the start location are the same and are a
1034 // macro location, then the range was something that came from a
1035 // macro expansion or _Pragma. If this is an object-like macro, the
1036 // best we can do is to highlight the range. If this is a
1037 // function-like macro, we'd also like to highlight the arguments.
1038 if (B == E && Info.getRange(i).getEnd().isMacroID())
Chandler Carruthedc3dcc2011-07-25 16:56:02 +00001039 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
Axel Naumann04331162011-01-27 10:55:51 +00001040
1041 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
1042 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
1043
1044 // If the start or end of the range is in another file, just discard
1045 // it.
1046 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
1047 continue;
1048
1049 // Add in the length of the token, so that we cover multi-char
1050 // tokens.
1051 unsigned TokSize = 0;
1052 if (Info.getRange(i).isTokenRange())
1053 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
1054
1055 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
1056 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
1057 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
1058 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
1059 << '}';
1060 PrintedRange = true;
1061 }
1062
1063 if (PrintedRange)
1064 OS << ':';
1065 }
Chris Lattner1fbee5d2009-03-13 01:08:23 +00001066 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001067 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +00001068 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001069 OS.resetColor();
1070 }
1071 }
1072
Daniel Dunbareace8742009-11-04 06:24:30 +00001073 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001074 // Print diagnostic category in bold and color
1075 switch (Level) {
1076 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
1077 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
1078 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
1079 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
1080 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +00001081 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001082 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001083
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +00001085 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +00001086 case Diagnostic::Note: OS << "note: "; break;
1087 case Diagnostic::Warning: OS << "warning: "; break;
1088 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +00001089 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001090 }
Torok Edwin603fca72009-06-04 07:18:23 +00001091
Daniel Dunbareace8742009-11-04 06:24:30 +00001092 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001093 OS.resetColor();
1094
Chris Lattnerf4c83962008-11-19 06:51:40 +00001095 llvm::SmallString<100> OutStr;
1096 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001097
Douglas Gregor7d2b8c12011-04-15 22:04:17 +00001098 if (DiagOpts->ShowNames &&
1099 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
1100 OutStr += " [";
1101 OutStr += DiagnosticIDs::getName(Info.getID());
1102 OutStr += "]";
1103 }
1104
Chris Lattnerc9b88902010-05-04 21:13:21 +00001105 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001106 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001107 // Was this a warning mapped to an error using -Werror or pragma?
1108 if (Level == Diagnostic::Error &&
1109 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
1110 diag::Mapping mapping = diag::MAP_IGNORE;
1111 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
1112 &mapping);
1113 if (mapping == diag::MAP_WARNING)
1114 OptionName += "-Werror";
1115 }
1116
Chris Lattner5f9e2722011-07-23 10:55:15 +00001117 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +00001118 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +00001119 if (!OptionName.empty())
1120 OptionName += ',';
1121 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +00001122 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +00001123 } else if (Info.getID() == diag::fatal_too_many_errors) {
1124 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +00001125 } else {
1126 // If the diagnostic is an extension diagnostic and not enabled by default
1127 // then it must have been turned on with -pedantic.
1128 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001129 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
1130 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +00001131 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +00001132 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001133 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +00001134 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001135
1136 // If the user wants to see category information, include it too.
1137 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +00001138 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001139 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001140
Chris Lattnerc9b88902010-05-04 21:13:21 +00001141 // If there is any categorization information, include it.
1142 if (!OptionName.empty() || DiagCategory != 0) {
1143 bool NeedsComma = false;
1144 OutStr += " [";
1145
1146 if (!OptionName.empty()) {
1147 OutStr += OptionName;
1148 NeedsComma = true;
1149 }
1150
1151 if (DiagCategory) {
1152 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +00001153 if (DiagOpts->ShowCategories == 1)
1154 OutStr += llvm::utostr(DiagCategory);
1155 else {
1156 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001157 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +00001158 }
Chris Lattnerc9b88902010-05-04 21:13:21 +00001159 }
1160
1161 OutStr += "]";
1162 }
1163
1164
Daniel Dunbareace8742009-11-04 06:24:30 +00001165 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +00001166 // Print warnings, errors and fatal errors in bold, no color
1167 switch (Level) {
1168 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
1169 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
1170 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
1171 default: break; //don't bold notes
1172 }
1173 }
1174
Daniel Dunbareace8742009-11-04 06:24:30 +00001175 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001176 // We will be word-wrapping the error message, so compute the
1177 // column number where we currently are (after printing the
1178 // location information).
1179 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001180 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001181 } else {
1182 OS.write(OutStr.begin(), OutStr.size());
1183 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001184 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001185 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001186 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001187
Douglas Gregordf667e72009-03-10 20:44:00 +00001188 // If caret diagnostics are enabled and we have location, we want to
1189 // emit the caret. However, we only do this if the location moved
1190 // from the last diagnostic, if the last diagnostic was a note that
1191 // was part of a different warning or error diagnostic, or if the
1192 // diagnostic has ranges. We don't want to emit the same caret
1193 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001194 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001195 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001196 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001197 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001198 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001199 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001200 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001201
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001202 // Get the ranges into a local array we can hack on.
Chris Lattner0a76aae2010-06-18 22:45:06 +00001203 CharSourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001204 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001205 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001206 for (unsigned i = 0; i != NumRanges; ++i)
1207 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001208
Douglas Gregor849b2432010-03-31 17:46:05 +00001209 unsigned NumHints = Info.getNumFixItHints();
Chris Lattner0a76aae2010-06-18 22:45:06 +00001210 for (unsigned i = 0; i != NumHints; ++i) {
1211 const FixItHint &Hint = Info.getFixItHint(i);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001212 if (Hint.RemoveRange.isValid()) {
1213 assert(NumRanges < 20 && "Out of space");
1214 Ranges[NumRanges++] = Hint.RemoveRange;
1215 }
1216 }
1217
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001218 const SourceManager &SM = LastLoc.getManager();
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001219 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1220 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001221 // Compute the length of the macro-expansion backtrace, so that we
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001222 // can establish which steps in the macro backtrace we'll skip.
1223 SourceLocation Loc = LastLoc;
1224 unsigned Depth = 0;
1225 do {
1226 ++Depth;
Chandler Carruth7e7736a2011-07-14 08:20:31 +00001227 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +00001228 Loc = getImmediateMacroCallerLoc(SM, Loc);
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001229 } while (!Loc.isFileID());
1230
1231 if (Depth > DiagOpts->MacroBacktraceLimit) {
1232 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1233 DiagOpts->MacroBacktraceLimit % 2;
1234 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1235 }
1236 }
1237
Chris Lattner83068312011-06-28 05:11:33 +00001238 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +00001239 Info.getFixItHints(),
1240 Info.getNumFixItHints(),
Chandler Carruth50c909b2011-08-31 23:59:23 +00001241 DiagOpts->MessageLength,
1242 MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001243 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001244
Chris Lattnera03a5b52008-11-19 06:56:25 +00001245 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001246}