blob: 04c6a68023d9863291b4fd1b37a79551979e91c8 [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
Torok Edwin603fca72009-06-04 07:18:23 +000026static const enum llvm::raw_ostream::Colors noteColor =
27 llvm::raw_ostream::BLACK;
28static const enum llvm::raw_ostream::Colors fixitColor =
29 llvm::raw_ostream::GREEN;
30static const enum llvm::raw_ostream::Colors caretColor =
31 llvm::raw_ostream::GREEN;
32static const enum llvm::raw_ostream::Colors warningColor =
33 llvm::raw_ostream::MAGENTA;
34static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
35static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000036// Used for changing only the bold attribute.
Torok Edwin603fca72009-06-04 07:18:23 +000037static const enum llvm::raw_ostream::Colors savedColor =
38 llvm::raw_ostream::SAVEDCOLOR;
39
Douglas Gregorfffd93f2009-05-01 21:53:04 +000040/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Daniel Dunbareace8742009-11-04 06:24:30 +000043TextDiagnosticPrinter::TextDiagnosticPrinter(llvm::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
Reid Spencer5f016e22007-07-11 17:01:13 +000056void TextDiagnosticPrinter::
Chris Lattnerb9c3f962009-01-27 07:57:44 +000057PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
58 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000059
Chris Lattnerb9c3f962009-01-27 07:57:44 +000060 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000061 if (PLoc.isInvalid())
62 return;
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064 // Print out the other include frames first.
Chris Lattnerb9c3f962009-01-27 07:57:44 +000065 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000066
Daniel Dunbareace8742009-11-04 06:24:30 +000067 if (DiagOpts->ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000068 OS << "In file included from " << PLoc.getFilename()
69 << ':' << PLoc.getLine() << ":\n";
70 else
71 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000072}
73
74/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
75/// any characters in LineNo that intersect the SourceRange.
Chris Lattner0a76aae2010-06-18 22:45:06 +000076void TextDiagnosticPrinter::HighlightRange(const CharSourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000077 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000078 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000079 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000080 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000081 assert(CaretLine.size() == SourceLine.size() &&
82 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000083 if (!R.isValid()) return;
84
Chris Lattnerb9c3f962009-01-27 07:57:44 +000085 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
86 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000087
Chris Lattner34837a52009-02-17 05:19:10 +000088 // If the End location and the start location are the same and are a macro
89 // location, then the range was something that came from a macro expansion
90 // or _Pragma. If this is an object-like macro, the best we can do is to
91 // highlight the range. If this is a function-like macro, we'd also like to
92 // highlight the arguments.
93 if (Begin == End && R.getEnd().isMacroID())
94 End = SM.getInstantiationRange(R.getEnd()).second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000095
Chris Lattner30fc9332009-02-04 01:06:56 +000096 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000097 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000098 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000099
Chris Lattner30fc9332009-02-04 01:06:56 +0000100 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000101 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +0000102 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000103
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 // Compute the column number of the start.
105 unsigned StartColNo = 0;
106 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000107 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 if (StartColNo) --StartColNo; // Zero base the col #.
109 }
110
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +0000112 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000114 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 if (EndColNo) {
116 --EndColNo; // Zero base the col #.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000117
Chris Lattner0a76aae2010-06-18 22:45:06 +0000118 // Add in the length of the token, so that we cover multi-char tokens if
119 // this is a token range.
120 if (R.isTokenRange())
121 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000123 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000124 }
125 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000126
Chris Lattner41e79e22010-02-12 18:52:52 +0000127 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000128
Tom Care45f9b7e2010-06-21 21:21:01 +0000129 // Check that a token range does not highlight only whitespace.
130 if (R.isTokenRange()) {
131 // Pick the first non-whitespace column.
132 while (StartColNo < SourceLine.size() &&
133 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
134 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000135
Tom Care45f9b7e2010-06-21 21:21:01 +0000136 // Pick the last non-whitespace column.
137 if (EndColNo > SourceLine.size())
138 EndColNo = SourceLine.size();
139 while (EndColNo-1 &&
140 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
141 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000142
Axel Naumann04331162011-01-27 10:55:51 +0000143 // If the start/end passed each other, then we are trying to highlight a
144 // range that just exists in whitespace, which must be some sort of other
145 // bug.
Tom Care45f9b7e2010-06-21 21:21:01 +0000146 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
147 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000150 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000151 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000152}
153
Douglas Gregor47f71772009-05-01 23:32:58 +0000154/// \brief When the source code line we want to print is too long for
155/// the terminal, select the "interesting" region.
156static void SelectInterestingSourceRegion(std::string &SourceLine,
157 std::string &CaretLine,
158 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000159 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000160 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000161 unsigned MaxSize = std::max(SourceLine.size(),
162 std::max(CaretLine.size(),
163 FixItInsertionLine.size()));
164 if (MaxSize > SourceLine.size())
165 SourceLine.resize(MaxSize, ' ');
166 if (MaxSize > CaretLine.size())
167 CaretLine.resize(MaxSize, ' ');
168 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
169 FixItInsertionLine.resize(MaxSize, ' ');
170
Douglas Gregor47f71772009-05-01 23:32:58 +0000171 // Find the slice that we need to display the full caret line
172 // correctly.
173 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
174 for (; CaretStart != CaretEnd; ++CaretStart)
175 if (!isspace(CaretLine[CaretStart]))
176 break;
177
178 for (; CaretEnd != CaretStart; --CaretEnd)
179 if (!isspace(CaretLine[CaretEnd - 1]))
180 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000181
182 // Make sure we don't chop the string shorter than the caret token
183 // itself.
184 if (CaretEnd < EndOfCaretToken)
185 CaretEnd = EndOfCaretToken;
186
Douglas Gregor844da342009-05-03 04:33:32 +0000187 // If we have a fix-it line, make sure the slice includes all of the
188 // fix-it information.
189 if (!FixItInsertionLine.empty()) {
190 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
191 for (; FixItStart != FixItEnd; ++FixItStart)
192 if (!isspace(FixItInsertionLine[FixItStart]))
193 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000194
Douglas Gregor844da342009-05-03 04:33:32 +0000195 for (; FixItEnd != FixItStart; --FixItEnd)
196 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
197 break;
198
199 if (FixItStart < CaretStart)
200 CaretStart = FixItStart;
201 if (FixItEnd > CaretEnd)
202 CaretEnd = FixItEnd;
203 }
204
Douglas Gregor47f71772009-05-01 23:32:58 +0000205 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
206 // parts of the caret line. While this slice is smaller than the
207 // number of columns we have, try to grow the slice to encompass
208 // more context.
209
210 // If the end of the interesting region comes before we run out of
211 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000212 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000213 CaretStart = 0;
214
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000215 unsigned TargetColumns = Columns;
216 if (TargetColumns > 8)
217 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000218 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000219 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000220 bool ExpandedRegion = false;
221 // Move the start of the interesting region left until we've
222 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000223 if (CaretStart == 1)
224 CaretStart = 0;
225 else if (CaretStart > 1) {
226 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000227
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000228 // Skip over any whitespace we see here; we're looking for
229 // another bit of interesting text.
230 while (NewStart && isspace(SourceLine[NewStart]))
231 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000232
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000233 // Skip over this bit of "interesting" text.
234 while (NewStart && !isspace(SourceLine[NewStart]))
235 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000236
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000237 // Move up to the non-whitespace character we just saw.
238 if (NewStart)
239 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000240
241 // If we're still within our limit, update the starting
242 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000243 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000244 CaretStart = NewStart;
245 ExpandedRegion = true;
246 }
247 }
248
249 // Move the end of the interesting region right until we've
250 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000251 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000252 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000253 unsigned NewEnd = CaretEnd;
254
255 // Skip over any whitespace we see here; we're looking for
256 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000257 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000258 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000259
Douglas Gregor47f71772009-05-01 23:32:58 +0000260 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000261 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000262 ++NewEnd;
263
264 if (NewEnd - CaretStart <= TargetColumns) {
265 CaretEnd = NewEnd;
266 ExpandedRegion = true;
267 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000268 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000269
270 if (!ExpandedRegion)
271 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000272 }
273
274 // [CaretStart, CaretEnd) is the slice we want. Update the various
275 // output lines to show only this slice, with two-space padding
276 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000277 if (CaretEnd < SourceLine.size())
278 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000279 if (CaretEnd < CaretLine.size())
280 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000281 if (FixItInsertionLine.size() > CaretEnd)
282 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000283
Douglas Gregor47f71772009-05-01 23:32:58 +0000284 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000285 SourceLine.replace(0, CaretStart, " ...");
286 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000287 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000288 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000289 }
290}
291
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000292void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000293 CharSourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000294 unsigned NumRanges,
Chris Lattner5c5db4e2010-04-20 20:49:23 +0000295 const SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000296 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000297 unsigned NumHints,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000298 unsigned Columns,
299 unsigned OnMacroInst,
300 unsigned MacroSkipStart,
301 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000302 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000303 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000304
305 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000306 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000307 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000308 if (!Loc.isFileID()) {
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000309 // Whether to suppress printing this macro instantiation.
310 bool Suppressed
311 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
312
313
Chris Lattner609b3ab2009-02-18 18:50:45 +0000314 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000315 // FIXME: Map ranges?
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000316 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns,
317 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
318
Chris Lattner2e77aa12009-12-04 07:06:35 +0000319 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000320 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000321
Chris Lattner676f0242009-02-20 00:25:28 +0000322 // Map the ranges.
323 for (unsigned i = 0; i != NumRanges; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +0000324 CharSourceRange &R = Ranges[i];
325 SourceLocation S = R.getBegin(), E = R.getEnd();
326 if (S.isMacroID())
327 R.setBegin(SM.getImmediateSpellingLoc(S));
328 if (E.isMacroID())
329 R.setEnd(SM.getImmediateSpellingLoc(E));
Chris Lattner676f0242009-02-20 00:25:28 +0000330 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000331
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000332 if (!Suppressed) {
333 // Get the pretty name, according to #line directives etc.
334 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000335 if (PLoc.isInvalid())
336 return;
337
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000338 // If this diagnostic is not in the main file, print out the
339 // "included from" lines.
340 if (LastWarningLoc != PLoc.getIncludeLoc()) {
341 LastWarningLoc = PLoc.getIncludeLoc();
342 PrintIncludeStack(LastWarningLoc, SM);
343 }
344
345 if (DiagOpts->ShowLocation) {
346 // Emit the file/line/column that this expansion came from.
347 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
348 if (DiagOpts->ShowColumn)
349 OS << PLoc.getColumn() << ':';
350 OS << ' ';
351 }
352 OS << "note: instantiated from:\n";
353
354 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns,
355 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
356 return;
Chris Lattner2e77aa12009-12-04 07:06:35 +0000357 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000358
359 if (OnMacroInst == MacroSkipStart) {
360 // Tell the user that we've skipped contexts.
361 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
362 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see "
363 "all)\n";
Chris Lattner5ce24c82009-04-21 03:57:54 +0000364 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000365
Chris Lattner037fb7f2009-05-05 22:03:18 +0000366 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000367 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000368
Chris Lattnerb88af812009-02-17 07:51:53 +0000369 // Decompose the location into a FID/Offset pair.
370 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
371 FileID FID = LocInfo.first;
372 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000373
Chris Lattnerb88af812009-02-17 07:51:53 +0000374 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000375 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000376 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000377 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000378 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000379
Chris Lattnerb88af812009-02-17 07:51:53 +0000380 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000381 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000382 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
383
Chris Lattner94f55782009-02-17 07:38:37 +0000384 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000385 const char *TokPtr = BufStart+FileOffset;
386 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000387
388
Chris Lattner94f55782009-02-17 07:38:37 +0000389 // Compute the line end. Scan forward from the error position to the end of
390 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000391 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000392 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000393 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000394
Daniel Dunbar06d10722009-10-19 09:11:21 +0000395 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
396 // the source line length as currently being computed. See
397 // test/Misc/message-length.c.
398 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
399
Chris Lattner94f55782009-02-17 07:38:37 +0000400 // Copy the line of code into an std::string for ease of manipulation.
401 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000402
Chris Lattner94f55782009-02-17 07:38:37 +0000403 // Create a line for the caret that is filled with spaces that is the same
404 // length as the line of source code.
405 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000406
Chris Lattner94f55782009-02-17 07:38:37 +0000407 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000408 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000409 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000410
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000411 for (unsigned i = 0, e = NumRanges; i != e; ++i)
412 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000413 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000414
Chris Lattner94f55782009-02-17 07:38:37 +0000415 // Next, insert the caret itself.
416 if (ColNo-1 < CaretLine.size())
417 CaretLine[ColNo-1] = '^';
418 else
419 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000420
Chris Lattner94f55782009-02-17 07:38:37 +0000421 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000422 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000423 for (unsigned i = 0; i != SourceLine.size(); ++i) {
424 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000425
Chris Lattner94f55782009-02-17 07:38:37 +0000426 // Replace this tab with at least one space.
427 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000428
Chris Lattner94f55782009-02-17 07:38:37 +0000429 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000430 unsigned TabStop = DiagOpts->TabStop;
431 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
432 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000433 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
434 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000435
Chris Lattner94f55782009-02-17 07:38:37 +0000436 // Insert spaces into the SourceLine.
437 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000438
Chris Lattner94f55782009-02-17 07:38:37 +0000439 // Insert spaces or ~'s into CaretLine.
440 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
441 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000442
Chris Lattner770dbf02009-04-28 22:33:16 +0000443 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
444 // produce easily machine parsable output. Add a space before the source line
445 // and the caret to make it trivial to tell the main diagnostic line from what
446 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000447 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000448 SourceLine = ' ' + SourceLine;
449 CaretLine = ' ' + CaretLine;
450 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000451
Douglas Gregor47f71772009-05-01 23:32:58 +0000452 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000453 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000454 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000455 Hint != LastHint; ++Hint) {
Douglas Gregor783c56f2010-08-18 14:24:02 +0000456 if (!Hint->CodeToInsert.empty()) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000457 // We have an insertion hint. Determine whether the inserted
458 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000459 std::pair<FileID, unsigned> HintLocInfo
Douglas Gregor783c56f2010-08-18 14:24:02 +0000460 = SM.getDecomposedInstantiationLoc(Hint->RemoveRange.getBegin());
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000461 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
462 SM.getLineNumber(FID, FileOffset)) {
463 // Insert the new code into the line just below the code
464 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000465 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000466 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000467 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000468 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000469 if (LastColumnModified > FixItInsertionLine.size())
470 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000471 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000472 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000473 } else {
474 FixItInsertionLine.clear();
475 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000476 }
477 }
478 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000479 // Now that we have the entire fixit line, expand the tabs in it.
480 // Since we don't want to insert spaces in the middle of a word,
481 // find each word and the column it should line up with and insert
482 // spaces until they match.
483 if (!FixItInsertionLine.empty()) {
484 unsigned FixItPos = 0;
485 unsigned LinePos = 0;
486 unsigned TabExpandedCol = 0;
487 unsigned LineLength = LineEnd - LineStart;
488
489 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
490 // Find the next word in the FixIt line.
491 while (FixItPos < FixItInsertionLine.size() &&
492 FixItInsertionLine[FixItPos] == ' ')
493 ++FixItPos;
494 unsigned CharDistance = FixItPos - TabExpandedCol;
495
496 // Walk forward in the source line, keeping track of
497 // the tab-expanded column.
498 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
499 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
500 ++TabExpandedCol;
501 else
502 TabExpandedCol =
503 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
504
505 // Adjust the fixit line to match this column.
506 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
507 FixItPos = TabExpandedCol;
508
509 // Walk to the end of the word.
510 while (FixItPos < FixItInsertionLine.size() &&
511 FixItInsertionLine[FixItPos] != ' ')
512 ++FixItPos;
513 }
514 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000515 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000516
Douglas Gregor47f71772009-05-01 23:32:58 +0000517 // If the source line is too long for our terminal, select only the
518 // "interesting" source region within that line.
519 if (Columns && SourceLine.size() > Columns)
520 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000521 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000522
Douglas Gregor47f71772009-05-01 23:32:58 +0000523 // Finally, remove any blank spaces from the end of CaretLine.
524 while (CaretLine[CaretLine.size()-1] == ' ')
525 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000526
Douglas Gregor47f71772009-05-01 23:32:58 +0000527 // Emit what we have computed.
528 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000529
Daniel Dunbareace8742009-11-04 06:24:30 +0000530 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000531 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000532 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000533 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000534 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000535
536 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000537 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000538 // Print fixit line in color
539 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000540 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000541 OS << ' ';
542 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000543 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000544 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000545 }
Douglas Gregor4786c152010-08-19 20:24:43 +0000546
547 if (DiagOpts->ShowParseableFixits) {
548
549 // We follow FixItRewriter's example in not (yet) handling
550 // fix-its in macros.
551 bool BadApples = false;
552 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
553 if (Hint->RemoveRange.isInvalid() ||
554 Hint->RemoveRange.getBegin().isMacroID() ||
555 Hint->RemoveRange.getEnd().isMacroID()) {
556 BadApples = true;
557 break;
558 }
559 }
560
561 if (!BadApples) {
562 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
563
564 SourceLocation B = Hint->RemoveRange.getBegin();
565 SourceLocation E = Hint->RemoveRange.getEnd();
566
567 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
568 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
569
570 // Adjust for token ranges.
571 if (Hint->RemoveRange.isTokenRange())
572 EInfo.second += Lexer::MeasureTokenLength(E, SM, *LangOpts);
573
574 // We specifically do not do word-wrapping or tab-expansion here,
575 // because this is supposed to be easy to parse.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000576 PresumedLoc PLoc = SM.getPresumedLoc(B);
577 if (PLoc.isInvalid())
578 break;
579
Douglas Gregorbf5e09d2010-08-20 03:17:33 +0000580 OS << "fix-it:\"";
Douglas Gregor4786c152010-08-19 20:24:43 +0000581 OS.write_escaped(SM.getPresumedLoc(B).getFilename());
582 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
583 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
584 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
585 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
Douglas Gregorbf5e09d2010-08-20 03:17:33 +0000586 << "}:\"";
Douglas Gregor4786c152010-08-19 20:24:43 +0000587 OS.write_escaped(Hint->CodeToInsert);
588 OS << "\"\n";
589 }
590 }
591 }
Chris Lattner94f55782009-02-17 07:38:37 +0000592}
593
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000594/// \brief Skip over whitespace in the string, starting at the given
595/// index.
596///
597/// \returns The index of the first non-whitespace character that is
598/// greater than or equal to Idx or, if no such character exists,
599/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000600static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000601 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000602 unsigned Length) {
603 while (Idx < Length && isspace(Str[Idx]))
604 ++Idx;
605 return Idx;
606}
607
608/// \brief If the given character is the start of some kind of
609/// balanced punctuation (e.g., quotes or parentheses), return the
610/// character that will terminate the punctuation.
611///
612/// \returns The ending punctuation character, if any, or the NULL
613/// character if the input character does not start any punctuation.
614static inline char findMatchingPunctuation(char c) {
615 switch (c) {
616 case '\'': return '\'';
617 case '`': return '\'';
618 case '"': return '"';
619 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000620 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000621 case '{': return '}';
622 default: break;
623 }
624
625 return 0;
626}
627
628/// \brief Find the end of the word starting at the given offset
629/// within a string.
630///
631/// \returns the index pointing one character past the end of the
632/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000633static unsigned findEndOfWord(unsigned Start,
634 const llvm::SmallVectorImpl<char> &Str,
635 unsigned Length, unsigned Column,
636 unsigned Columns) {
637 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000638 unsigned End = Start + 1;
639
Daniel Dunbareae18f82009-12-06 09:56:18 +0000640 // If we are already at the end of the string, take that as the word.
641 if (End == Str.size())
642 return End;
643
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000644 // Determine if the start of the string is actually opening
645 // punctuation, e.g., a quote or parentheses.
646 char EndPunct = findMatchingPunctuation(Str[Start]);
647 if (!EndPunct) {
648 // This is a normal word. Just find the first space character.
649 while (End < Length && !isspace(Str[End]))
650 ++End;
651 return End;
652 }
653
654 // We have the start of a balanced punctuation sequence (quotes,
655 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000656 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000657 PunctuationEndStack.push_back(EndPunct);
658 while (End < Length && !PunctuationEndStack.empty()) {
659 if (Str[End] == PunctuationEndStack.back())
660 PunctuationEndStack.pop_back();
661 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
662 PunctuationEndStack.push_back(SubEndPunct);
663
664 ++End;
665 }
666
667 // Find the first space character after the punctuation ended.
668 while (End < Length && !isspace(Str[End]))
669 ++End;
670
671 unsigned PunctWordLength = End - Start;
672 if (// If the word fits on this line
673 Column + PunctWordLength <= Columns ||
674 // ... or the word is "short enough" to take up the next line
675 // without too much ugly white space
676 PunctWordLength < Columns/3)
677 return End; // Take the whole thing as a single "word".
678
679 // The whole quoted/parenthesized string is too long to print as a
680 // single "word". Instead, find the "word" that starts just after
681 // the punctuation and use that end-point instead. This will recurse
682 // until it finds something small enough to consider a word.
683 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
684}
685
686/// \brief Print the given string to a stream, word-wrapping it to
687/// some number of columns in the process.
688///
689/// \brief OS the stream to which the word-wrapping string will be
690/// emitted.
691///
692/// \brief Str the string to word-wrap and output.
693///
694/// \brief Columns the number of columns to word-wrap to.
695///
696/// \brief Column the column number at which the first character of \p
697/// Str will be printed. This will be non-zero when part of the first
698/// line has already been printed.
699///
700/// \brief Indentation the number of spaces to indent any lines beyond
701/// the first line.
702///
703/// \returns true if word-wrapping was required, or false if the
704/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000705static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000706 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000707 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000708 unsigned Column = 0,
709 unsigned Indentation = WordWrapIndentation) {
710 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000711
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000712 // If there is a newline in this message somewhere, find that
713 // newline and split the message into the part before the newline
714 // (which will be word-wrapped) and the part from the newline one
715 // (which will be emitted unchanged).
716 for (unsigned I = 0; I != Length; ++I)
717 if (Str[I] == '\n') {
718 Length = I;
719 break;
720 }
721
722 // The string used to indent each line.
723 llvm::SmallString<16> IndentStr;
724 IndentStr.assign(Indentation, ' ');
725 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000726 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000727 WordStart = WordEnd) {
728 // Find the beginning of the next word.
729 WordStart = skipWhitespace(WordStart, Str, Length);
730 if (WordStart == Length)
731 break;
732
733 // Find the end of this word.
734 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000735
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000736 // Does this word fit on the current line?
737 unsigned WordLength = WordEnd - WordStart;
738 if (Column + WordLength < Columns) {
739 // This word fits on the current line; print it there.
740 if (WordStart) {
741 OS << ' ';
742 Column += 1;
743 }
744 OS.write(&Str[WordStart], WordLength);
745 Column += WordLength;
746 continue;
747 }
748
749 // This word does not fit on the current line, so wrap to the next
750 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000751 OS << '\n';
752 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000753 OS.write(&Str[WordStart], WordLength);
754 Column = Indentation + WordLength;
755 Wrapped = true;
756 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000757
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000758 if (Length == Str.size())
759 return Wrapped; // We're done.
760
761 // There is a newline in the message, followed by something that
762 // will not be word-wrapped. Print that.
763 OS.write(&Str[Length], Str.size() - Length);
764 return true;
765}
Chris Lattner94f55782009-02-17 07:38:37 +0000766
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000767void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000768 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000769 // Default implementation (Warnings/errors count).
770 DiagnosticClient::HandleDiagnostic(Level, Info);
771
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000772 // Keeps track of the the starting position of the location
773 // information (e.g., "foo.c:10:4:") that precedes the error
774 // message. We use this information to determine how long the
775 // file+line+column number prefix is.
776 uint64_t StartOfLocationInfo = OS.tell();
777
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000778 if (!Prefix.empty())
779 OS << Prefix << ": ";
780
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000781 // If the location is specified, print out a file/line/col and include trace
782 // if enabled.
783 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000784 const SourceManager &SM = Info.getSourceManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000785 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
Axel Naumann04331162011-01-27 10:55:51 +0000786 if (PLoc.isInvalid()) {
787 // At least print the file name if available:
788 FileID FID = SM.getFileID(Info.getLocation());
789 if (!FID.isInvalid()) {
790 const FileEntry* FE = SM.getFileEntryForID(FID);
791 if (FE && FE->getName()) {
792 OS << FE->getName();
793 if (FE->getDevice() == 0 && FE->getInode() == 0
794 && FE->getFileMode() == 0) {
795 // in PCH is a guess, but a good one:
796 OS << " (in PCH)";
797 }
798 OS << ": ";
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000799 }
Axel Naumann04331162011-01-27 10:55:51 +0000800 }
801 } else {
802 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000803
Axel Naumann04331162011-01-27 10:55:51 +0000804 // First, if this diagnostic is not in the main file, print out the
805 // "included from" lines.
806 if (LastWarningLoc != PLoc.getIncludeLoc()) {
807 LastWarningLoc = PLoc.getIncludeLoc();
808 PrintIncludeStack(LastWarningLoc, SM);
809 StartOfLocationInfo = OS.tell();
810 }
811
812 // Compute the column number.
813 if (DiagOpts->ShowLocation && PLoc.isValid()) {
814 if (DiagOpts->ShowColors)
815 OS.changeColor(savedColor, true);
816
817 // Emit a Visual Studio compatible line number syntax.
818 if (LangOpts && LangOpts->Microsoft) {
819 OS << PLoc.getFilename() << '(' << LineNo << ')';
820 OS << " : ";
821 } else {
822 OS << PLoc.getFilename() << ':' << LineNo << ':';
823 if (DiagOpts->ShowColumn)
824 if (unsigned ColNo = PLoc.getColumn())
825 OS << ColNo << ':';
826 }
827 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
828 FileID CaretFileID =
829 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
830 bool PrintedRange = false;
831
832 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
833 // Ignore invalid ranges.
834 if (!Info.getRange(i).isValid()) continue;
835
836 SourceLocation B = Info.getRange(i).getBegin();
837 SourceLocation E = Info.getRange(i).getEnd();
838 B = SM.getInstantiationLoc(B);
839 E = SM.getInstantiationLoc(E);
840
841 // If the End location and the start location are the same and are a
842 // macro location, then the range was something that came from a
843 // macro expansion or _Pragma. If this is an object-like macro, the
844 // best we can do is to highlight the range. If this is a
845 // function-like macro, we'd also like to highlight the arguments.
846 if (B == E && Info.getRange(i).getEnd().isMacroID())
847 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
848
849 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
850 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
851
852 // If the start or end of the range is in another file, just discard
853 // it.
854 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
855 continue;
856
857 // Add in the length of the token, so that we cover multi-char
858 // tokens.
859 unsigned TokSize = 0;
860 if (Info.getRange(i).isTokenRange())
861 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
862
863 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
864 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
865 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
866 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
867 << '}';
868 PrintedRange = true;
869 }
870
871 if (PrintedRange)
872 OS << ':';
873 }
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000874 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000875 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000876 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000877 OS.resetColor();
878 }
879 }
880
Daniel Dunbareace8742009-11-04 06:24:30 +0000881 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000882 // Print diagnostic category in bold and color
883 switch (Level) {
884 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
885 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
886 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
887 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
888 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000889 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000890 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000891
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000893 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000894 case Diagnostic::Note: OS << "note: "; break;
895 case Diagnostic::Warning: OS << "warning: "; break;
896 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000897 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 }
Torok Edwin603fca72009-06-04 07:18:23 +0000899
Daniel Dunbareace8742009-11-04 06:24:30 +0000900 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000901 OS.resetColor();
902
Chris Lattnerf4c83962008-11-19 06:51:40 +0000903 llvm::SmallString<100> OutStr;
904 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000905
Chris Lattnerc9b88902010-05-04 21:13:21 +0000906 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000907 if (DiagOpts->ShowOptionNames) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000908 if (const char *
909 Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID())) {
Chris Lattnerc9b88902010-05-04 21:13:21 +0000910 OptionName = "-W";
911 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +0000912 } else if (Info.getID() == diag::fatal_too_many_errors) {
913 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +0000914 } else {
915 // If the diagnostic is an extension diagnostic and not enabled by default
916 // then it must have been turned on with -pedantic.
917 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000918 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
919 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +0000920 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000921 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000922 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000923 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000924
925 // If the user wants to see category information, include it too.
926 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +0000927 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000928 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000929
Chris Lattnerc9b88902010-05-04 21:13:21 +0000930 // If there is any categorization information, include it.
931 if (!OptionName.empty() || DiagCategory != 0) {
932 bool NeedsComma = false;
933 OutStr += " [";
934
935 if (!OptionName.empty()) {
936 OutStr += OptionName;
937 NeedsComma = true;
938 }
939
940 if (DiagCategory) {
941 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +0000942 if (DiagOpts->ShowCategories == 1)
943 OutStr += llvm::utostr(DiagCategory);
944 else {
945 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000946 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +0000947 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000948 }
949
950 OutStr += "]";
951 }
952
953
Daniel Dunbareace8742009-11-04 06:24:30 +0000954 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000955 // Print warnings, errors and fatal errors in bold, no color
956 switch (Level) {
957 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
958 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
959 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
960 default: break; //don't bold notes
961 }
962 }
963
Daniel Dunbareace8742009-11-04 06:24:30 +0000964 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000965 // We will be word-wrapping the error message, so compute the
966 // column number where we currently are (after printing the
967 // location information).
968 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +0000969 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000970 } else {
971 OS.write(OutStr.begin(), OutStr.size());
972 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000973 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000974 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000975 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000976
Douglas Gregordf667e72009-03-10 20:44:00 +0000977 // If caret diagnostics are enabled and we have location, we want to
978 // emit the caret. However, we only do this if the location moved
979 // from the last diagnostic, if the last diagnostic was a note that
980 // was part of a different warning or error diagnostic, or if the
981 // diagnostic has ranges. We don't want to emit the same caret
982 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +0000983 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000984 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000985 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +0000986 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000987 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000988 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +0000989 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000990
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000991 // Get the ranges into a local array we can hack on.
Chris Lattner0a76aae2010-06-18 22:45:06 +0000992 CharSourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000993 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000994 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000995 for (unsigned i = 0; i != NumRanges; ++i)
996 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000997
Douglas Gregor849b2432010-03-31 17:46:05 +0000998 unsigned NumHints = Info.getNumFixItHints();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000999 for (unsigned i = 0; i != NumHints; ++i) {
1000 const FixItHint &Hint = Info.getFixItHint(i);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001001 if (Hint.RemoveRange.isValid()) {
1002 assert(NumRanges < 20 && "Out of space");
1003 Ranges[NumRanges++] = Hint.RemoveRange;
1004 }
1005 }
1006
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001007 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1008 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
1009 // Compute the length of the macro-instantiation backtrace, so that we
1010 // can establish which steps in the macro backtrace we'll skip.
1011 SourceLocation Loc = LastLoc;
1012 unsigned Depth = 0;
1013 do {
1014 ++Depth;
1015 Loc = LastLoc.getManager().getImmediateInstantiationRange(Loc).first;
1016 } while (!Loc.isFileID());
1017
1018 if (Depth > DiagOpts->MacroBacktraceLimit) {
1019 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1020 DiagOpts->MacroBacktraceLimit % 2;
1021 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1022 }
1023 }
1024
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001025 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +00001026 Info.getFixItHints(),
1027 Info.getNumFixItHints(),
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001028 DiagOpts->MessageLength,
1029 0, MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001030 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001031
Chris Lattnera03a5b52008-11-19 06:56:25 +00001032 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001033}