blob: affa12babe573dbce501c6bd36485c87b4405c60 [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
Chandler Carruthabaca7a2011-03-27 01:50:55 +000056void TextDiagnosticPrinter::PrintIncludeStack(Diagnostic::Level Level,
57 SourceLocation Loc,
58 const SourceManager &SM) {
59 if (!DiagOpts->ShowNoteIncludeStack && Level == Diagnostic::Note) return;
60
Chris Lattnerb9c3f962009-01-27 07:57:44 +000061 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000062
Chris Lattnerb9c3f962009-01-27 07:57:44 +000063 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000064 if (PLoc.isInvalid())
65 return;
66
Reid Spencer5f016e22007-07-11 17:01:13 +000067 // Print out the other include frames first.
Chandler Carruthabaca7a2011-03-27 01:50:55 +000068 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000069
Daniel Dunbareace8742009-11-04 06:24:30 +000070 if (DiagOpts->ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000071 OS << "In file included from " << PLoc.getFilename()
72 << ':' << PLoc.getLine() << ":\n";
73 else
74 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
77/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
78/// any characters in LineNo that intersect the SourceRange.
Chris Lattner0a76aae2010-06-18 22:45:06 +000079void TextDiagnosticPrinter::HighlightRange(const CharSourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000080 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000081 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000082 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000083 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000084 assert(CaretLine.size() == SourceLine.size() &&
85 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000086 if (!R.isValid()) return;
87
Chris Lattnerb9c3f962009-01-27 07:57:44 +000088 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
89 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000090
Chris Lattner34837a52009-02-17 05:19:10 +000091 // If the End location and the start location are the same and are a macro
92 // location, then the range was something that came from a macro expansion
93 // or _Pragma. If this is an object-like macro, the best we can do is to
94 // highlight the range. If this is a function-like macro, we'd also like to
95 // highlight the arguments.
96 if (Begin == End && R.getEnd().isMacroID())
97 End = SM.getInstantiationRange(R.getEnd()).second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000098
Chris Lattner30fc9332009-02-04 01:06:56 +000099 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000100 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +0000101 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000102
Chris Lattner30fc9332009-02-04 01:06:56 +0000103 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000104 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +0000105 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 // Compute the column number of the start.
108 unsigned StartColNo = 0;
109 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000110 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 if (StartColNo) --StartColNo; // Zero base the col #.
112 }
113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +0000115 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000117 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 if (EndColNo) {
119 --EndColNo; // Zero base the col #.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000120
Chris Lattner0a76aae2010-06-18 22:45:06 +0000121 // Add in the length of the token, so that we cover multi-char tokens if
122 // this is a token range.
123 if (R.isTokenRange())
124 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000126 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000129
Chris Lattner41e79e22010-02-12 18:52:52 +0000130 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000131
Tom Care45f9b7e2010-06-21 21:21:01 +0000132 // Check that a token range does not highlight only whitespace.
133 if (R.isTokenRange()) {
134 // Pick the first non-whitespace column.
135 while (StartColNo < SourceLine.size() &&
136 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
137 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000138
Tom Care45f9b7e2010-06-21 21:21:01 +0000139 // Pick the last non-whitespace column.
140 if (EndColNo > SourceLine.size())
141 EndColNo = SourceLine.size();
142 while (EndColNo-1 &&
143 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
144 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000145
Axel Naumann04331162011-01-27 10:55:51 +0000146 // If the start/end passed each other, then we are trying to highlight a
147 // range that just exists in whitespace, which must be some sort of other
148 // bug.
Tom Care45f9b7e2010-06-21 21:21:01 +0000149 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
150 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000151
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000153 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000154 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000155}
156
Douglas Gregor47f71772009-05-01 23:32:58 +0000157/// \brief When the source code line we want to print is too long for
158/// the terminal, select the "interesting" region.
159static void SelectInterestingSourceRegion(std::string &SourceLine,
160 std::string &CaretLine,
161 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000162 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000163 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000164 unsigned MaxSize = std::max(SourceLine.size(),
165 std::max(CaretLine.size(),
166 FixItInsertionLine.size()));
167 if (MaxSize > SourceLine.size())
168 SourceLine.resize(MaxSize, ' ');
169 if (MaxSize > CaretLine.size())
170 CaretLine.resize(MaxSize, ' ');
171 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
172 FixItInsertionLine.resize(MaxSize, ' ');
173
Douglas Gregor47f71772009-05-01 23:32:58 +0000174 // Find the slice that we need to display the full caret line
175 // correctly.
176 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
177 for (; CaretStart != CaretEnd; ++CaretStart)
178 if (!isspace(CaretLine[CaretStart]))
179 break;
180
181 for (; CaretEnd != CaretStart; --CaretEnd)
182 if (!isspace(CaretLine[CaretEnd - 1]))
183 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000184
185 // Make sure we don't chop the string shorter than the caret token
186 // itself.
187 if (CaretEnd < EndOfCaretToken)
188 CaretEnd = EndOfCaretToken;
189
Douglas Gregor844da342009-05-03 04:33:32 +0000190 // If we have a fix-it line, make sure the slice includes all of the
191 // fix-it information.
192 if (!FixItInsertionLine.empty()) {
193 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
194 for (; FixItStart != FixItEnd; ++FixItStart)
195 if (!isspace(FixItInsertionLine[FixItStart]))
196 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000197
Douglas Gregor844da342009-05-03 04:33:32 +0000198 for (; FixItEnd != FixItStart; --FixItEnd)
199 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
200 break;
201
202 if (FixItStart < CaretStart)
203 CaretStart = FixItStart;
204 if (FixItEnd > CaretEnd)
205 CaretEnd = FixItEnd;
206 }
207
Douglas Gregor47f71772009-05-01 23:32:58 +0000208 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
209 // parts of the caret line. While this slice is smaller than the
210 // number of columns we have, try to grow the slice to encompass
211 // more context.
212
213 // If the end of the interesting region comes before we run out of
214 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000215 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000216 CaretStart = 0;
217
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000218 unsigned TargetColumns = Columns;
219 if (TargetColumns > 8)
220 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000221 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000222 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000223 bool ExpandedRegion = false;
224 // Move the start of the interesting region left until we've
225 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000226 if (CaretStart == 1)
227 CaretStart = 0;
228 else if (CaretStart > 1) {
229 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000230
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000231 // Skip over any whitespace we see here; we're looking for
232 // another bit of interesting text.
233 while (NewStart && isspace(SourceLine[NewStart]))
234 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000235
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000236 // Skip over this bit of "interesting" text.
237 while (NewStart && !isspace(SourceLine[NewStart]))
238 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000239
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000240 // Move up to the non-whitespace character we just saw.
241 if (NewStart)
242 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000243
244 // If we're still within our limit, update the starting
245 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000246 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000247 CaretStart = NewStart;
248 ExpandedRegion = true;
249 }
250 }
251
252 // Move the end of the interesting region right until we've
253 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000254 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000255 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000256 unsigned NewEnd = CaretEnd;
257
258 // Skip over any whitespace we see here; we're looking for
259 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000260 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000261 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000262
Douglas Gregor47f71772009-05-01 23:32:58 +0000263 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000264 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000265 ++NewEnd;
266
267 if (NewEnd - CaretStart <= TargetColumns) {
268 CaretEnd = NewEnd;
269 ExpandedRegion = true;
270 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000271 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000272
273 if (!ExpandedRegion)
274 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000275 }
276
277 // [CaretStart, CaretEnd) is the slice we want. Update the various
278 // output lines to show only this slice, with two-space padding
279 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000280 if (CaretEnd < SourceLine.size())
281 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000282 if (CaretEnd < CaretLine.size())
283 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000284 if (FixItInsertionLine.size() > CaretEnd)
285 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000286
Douglas Gregor47f71772009-05-01 23:32:58 +0000287 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000288 SourceLine.replace(0, CaretStart, " ...");
289 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000290 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000291 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000292 }
293}
294
Chris Lattner83068312011-06-28 05:11:33 +0000295void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000296 CharSourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000297 unsigned NumRanges,
Chris Lattner5c5db4e2010-04-20 20:49:23 +0000298 const SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000299 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000300 unsigned NumHints,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000301 unsigned Columns,
302 unsigned OnMacroInst,
303 unsigned MacroSkipStart,
304 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000305 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000306 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000307
308 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000309 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000310 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000311 if (!Loc.isFileID()) {
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000312 // Whether to suppress printing this macro instantiation.
313 bool Suppressed
314 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
315
Chris Lattner609b3ab2009-02-18 18:50:45 +0000316 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner83068312011-06-28 05:11:33 +0000317
Chris Lattner037fb7f2009-05-05 22:03:18 +0000318 // FIXME: Map ranges?
Chris Lattner83068312011-06-28 05:11:33 +0000319 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM,
Argyrios Kyrtzidis544607e2011-06-24 17:28:31 +0000320 Hints, NumHints, Columns,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000321 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
322
Chris Lattner2e77aa12009-12-04 07:06:35 +0000323 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000324 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000325
Chris Lattner676f0242009-02-20 00:25:28 +0000326 // Map the ranges.
327 for (unsigned i = 0; i != NumRanges; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +0000328 CharSourceRange &R = Ranges[i];
329 SourceLocation S = R.getBegin(), E = R.getEnd();
330 if (S.isMacroID())
331 R.setBegin(SM.getImmediateSpellingLoc(S));
332 if (E.isMacroID())
333 R.setEnd(SM.getImmediateSpellingLoc(E));
Chris Lattner676f0242009-02-20 00:25:28 +0000334 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000335
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000336 if (!Suppressed) {
337 // Get the pretty name, according to #line directives etc.
338 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000339 if (PLoc.isInvalid())
340 return;
341
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000342 // If this diagnostic is not in the main file, print out the
343 // "included from" lines.
344 if (LastWarningLoc != PLoc.getIncludeLoc()) {
345 LastWarningLoc = PLoc.getIncludeLoc();
Richard Trieubb6a5672011-05-26 20:49:16 +0000346 PrintIncludeStack(Diagnostic::Note, LastWarningLoc, SM);
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000347 }
348
349 if (DiagOpts->ShowLocation) {
350 // Emit the file/line/column that this expansion came from.
351 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
352 if (DiagOpts->ShowColumn)
353 OS << PLoc.getColumn() << ':';
354 OS << ' ';
355 }
356 OS << "note: instantiated from:\n";
357
Chris Lattner83068312011-06-28 05:11:33 +0000358 // Don't print recursive instantiation notes from an instantiation note.
359 Loc = SM.getSpellingLoc(Loc);
360
361 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, 0, 0,
Chandler Carruthabaca7a2011-03-27 01:50:55 +0000362 Columns, OnMacroInst + 1, MacroSkipStart,
363 MacroSkipEnd);
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000364 return;
Chris Lattner2e77aa12009-12-04 07:06:35 +0000365 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000366
367 if (OnMacroInst == MacroSkipStart) {
368 // Tell the user that we've skipped contexts.
369 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
370 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see "
371 "all)\n";
Chris Lattner5ce24c82009-04-21 03:57:54 +0000372 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000373
Chris Lattner037fb7f2009-05-05 22:03:18 +0000374 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000375 }
Chris Lattner83068312011-06-28 05:11:33 +0000376
Chris Lattnerb88af812009-02-17 07:51:53 +0000377 // Decompose the location into a FID/Offset pair.
378 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
379 FileID FID = LocInfo.first;
380 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000381
Chris Lattnerb88af812009-02-17 07:51:53 +0000382 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000383 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000384 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000385 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000386 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000387
Chris Lattnerb88af812009-02-17 07:51:53 +0000388 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000389 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000390 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
391
Chris Lattner94f55782009-02-17 07:38:37 +0000392 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000393 const char *TokPtr = BufStart+FileOffset;
394 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000395
396
Chris Lattner94f55782009-02-17 07:38:37 +0000397 // Compute the line end. Scan forward from the error position to the end of
398 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000399 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000400 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000401 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000402
Daniel Dunbar06d10722009-10-19 09:11:21 +0000403 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
404 // the source line length as currently being computed. See
405 // test/Misc/message-length.c.
406 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
407
Chris Lattner94f55782009-02-17 07:38:37 +0000408 // Copy the line of code into an std::string for ease of manipulation.
409 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000410
Chris Lattner94f55782009-02-17 07:38:37 +0000411 // Create a line for the caret that is filled with spaces that is the same
412 // length as the line of source code.
413 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000414
Chris Lattner94f55782009-02-17 07:38:37 +0000415 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000416 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000417 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000418
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000419 for (unsigned i = 0, e = NumRanges; i != e; ++i)
420 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000421 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000422
Chris Lattner94f55782009-02-17 07:38:37 +0000423 // Next, insert the caret itself.
424 if (ColNo-1 < CaretLine.size())
425 CaretLine[ColNo-1] = '^';
426 else
427 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000428
Chris Lattner94f55782009-02-17 07:38:37 +0000429 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000430 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000431 for (unsigned i = 0; i != SourceLine.size(); ++i) {
432 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000433
Chris Lattner94f55782009-02-17 07:38:37 +0000434 // Replace this tab with at least one space.
435 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000436
Chris Lattner94f55782009-02-17 07:38:37 +0000437 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000438 unsigned TabStop = DiagOpts->TabStop;
439 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
440 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000441 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
442 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000443
Chris Lattner94f55782009-02-17 07:38:37 +0000444 // Insert spaces into the SourceLine.
445 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000446
Chris Lattner94f55782009-02-17 07:38:37 +0000447 // Insert spaces or ~'s into CaretLine.
448 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
449 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000450
Chris Lattner770dbf02009-04-28 22:33:16 +0000451 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
452 // produce easily machine parsable output. Add a space before the source line
453 // and the caret to make it trivial to tell the main diagnostic line from what
454 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000455 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000456 SourceLine = ' ' + SourceLine;
457 CaretLine = ' ' + CaretLine;
458 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000459
Douglas Gregor47f71772009-05-01 23:32:58 +0000460 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000461 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000462 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000463 Hint != LastHint; ++Hint) {
Douglas Gregor783c56f2010-08-18 14:24:02 +0000464 if (!Hint->CodeToInsert.empty()) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000465 // We have an insertion hint. Determine whether the inserted
466 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000467 std::pair<FileID, unsigned> HintLocInfo
Douglas Gregor783c56f2010-08-18 14:24:02 +0000468 = SM.getDecomposedInstantiationLoc(Hint->RemoveRange.getBegin());
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000469 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
470 SM.getLineNumber(FID, FileOffset)) {
471 // Insert the new code into the line just below the code
472 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000473 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000474 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000475 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000476 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000477 if (LastColumnModified > FixItInsertionLine.size())
478 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000479 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000480 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000481 } else {
482 FixItInsertionLine.clear();
483 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000484 }
485 }
486 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000487 // Now that we have the entire fixit line, expand the tabs in it.
488 // Since we don't want to insert spaces in the middle of a word,
489 // find each word and the column it should line up with and insert
490 // spaces until they match.
491 if (!FixItInsertionLine.empty()) {
492 unsigned FixItPos = 0;
493 unsigned LinePos = 0;
494 unsigned TabExpandedCol = 0;
495 unsigned LineLength = LineEnd - LineStart;
496
497 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
498 // Find the next word in the FixIt line.
499 while (FixItPos < FixItInsertionLine.size() &&
500 FixItInsertionLine[FixItPos] == ' ')
501 ++FixItPos;
502 unsigned CharDistance = FixItPos - TabExpandedCol;
503
504 // Walk forward in the source line, keeping track of
505 // the tab-expanded column.
506 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
507 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
508 ++TabExpandedCol;
509 else
510 TabExpandedCol =
511 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
512
513 // Adjust the fixit line to match this column.
514 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
515 FixItPos = TabExpandedCol;
516
517 // Walk to the end of the word.
518 while (FixItPos < FixItInsertionLine.size() &&
519 FixItInsertionLine[FixItPos] != ' ')
520 ++FixItPos;
521 }
522 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000523 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000524
Douglas Gregor47f71772009-05-01 23:32:58 +0000525 // If the source line is too long for our terminal, select only the
526 // "interesting" source region within that line.
527 if (Columns && SourceLine.size() > Columns)
528 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000529 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000530
Douglas Gregor47f71772009-05-01 23:32:58 +0000531 // Finally, remove any blank spaces from the end of CaretLine.
532 while (CaretLine[CaretLine.size()-1] == ' ')
533 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000534
Douglas Gregor47f71772009-05-01 23:32:58 +0000535 // Emit what we have computed.
536 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000537
Daniel Dunbareace8742009-11-04 06:24:30 +0000538 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000539 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000540 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000541 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000542 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000543
544 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000545 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000546 // Print fixit line in color
547 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000548 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000549 OS << ' ';
550 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000551 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000552 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000553 }
Douglas Gregor4786c152010-08-19 20:24:43 +0000554
555 if (DiagOpts->ShowParseableFixits) {
556
557 // We follow FixItRewriter's example in not (yet) handling
558 // fix-its in macros.
559 bool BadApples = false;
560 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
561 if (Hint->RemoveRange.isInvalid() ||
562 Hint->RemoveRange.getBegin().isMacroID() ||
563 Hint->RemoveRange.getEnd().isMacroID()) {
564 BadApples = true;
565 break;
566 }
567 }
568
569 if (!BadApples) {
570 for (const FixItHint *Hint = Hints; Hint != Hints + NumHints; ++Hint) {
571
572 SourceLocation B = Hint->RemoveRange.getBegin();
573 SourceLocation E = Hint->RemoveRange.getEnd();
574
575 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
576 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
577
578 // Adjust for token ranges.
579 if (Hint->RemoveRange.isTokenRange())
580 EInfo.second += Lexer::MeasureTokenLength(E, SM, *LangOpts);
581
582 // We specifically do not do word-wrapping or tab-expansion here,
583 // because this is supposed to be easy to parse.
Douglas Gregorcb7b1e12010-11-12 07:15:47 +0000584 PresumedLoc PLoc = SM.getPresumedLoc(B);
585 if (PLoc.isInvalid())
586 break;
587
Douglas Gregorbf5e09d2010-08-20 03:17:33 +0000588 OS << "fix-it:\"";
Douglas Gregor4786c152010-08-19 20:24:43 +0000589 OS.write_escaped(SM.getPresumedLoc(B).getFilename());
590 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
591 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
592 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
593 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
Douglas Gregorbf5e09d2010-08-20 03:17:33 +0000594 << "}:\"";
Douglas Gregor4786c152010-08-19 20:24:43 +0000595 OS.write_escaped(Hint->CodeToInsert);
596 OS << "\"\n";
597 }
598 }
599 }
Chris Lattner94f55782009-02-17 07:38:37 +0000600}
601
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000602/// \brief Skip over whitespace in the string, starting at the given
603/// index.
604///
605/// \returns The index of the first non-whitespace character that is
606/// greater than or equal to Idx or, if no such character exists,
607/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000608static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000609 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000610 unsigned Length) {
611 while (Idx < Length && isspace(Str[Idx]))
612 ++Idx;
613 return Idx;
614}
615
616/// \brief If the given character is the start of some kind of
617/// balanced punctuation (e.g., quotes or parentheses), return the
618/// character that will terminate the punctuation.
619///
620/// \returns The ending punctuation character, if any, or the NULL
621/// character if the input character does not start any punctuation.
622static inline char findMatchingPunctuation(char c) {
623 switch (c) {
624 case '\'': return '\'';
625 case '`': return '\'';
626 case '"': return '"';
627 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000628 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000629 case '{': return '}';
630 default: break;
631 }
632
633 return 0;
634}
635
636/// \brief Find the end of the word starting at the given offset
637/// within a string.
638///
639/// \returns the index pointing one character past the end of the
640/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000641static unsigned findEndOfWord(unsigned Start,
642 const llvm::SmallVectorImpl<char> &Str,
643 unsigned Length, unsigned Column,
644 unsigned Columns) {
645 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000646 unsigned End = Start + 1;
647
Daniel Dunbareae18f82009-12-06 09:56:18 +0000648 // If we are already at the end of the string, take that as the word.
649 if (End == Str.size())
650 return End;
651
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000652 // Determine if the start of the string is actually opening
653 // punctuation, e.g., a quote or parentheses.
654 char EndPunct = findMatchingPunctuation(Str[Start]);
655 if (!EndPunct) {
656 // This is a normal word. Just find the first space character.
657 while (End < Length && !isspace(Str[End]))
658 ++End;
659 return End;
660 }
661
662 // We have the start of a balanced punctuation sequence (quotes,
663 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000664 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000665 PunctuationEndStack.push_back(EndPunct);
666 while (End < Length && !PunctuationEndStack.empty()) {
667 if (Str[End] == PunctuationEndStack.back())
668 PunctuationEndStack.pop_back();
669 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
670 PunctuationEndStack.push_back(SubEndPunct);
671
672 ++End;
673 }
674
675 // Find the first space character after the punctuation ended.
676 while (End < Length && !isspace(Str[End]))
677 ++End;
678
679 unsigned PunctWordLength = End - Start;
680 if (// If the word fits on this line
681 Column + PunctWordLength <= Columns ||
682 // ... or the word is "short enough" to take up the next line
683 // without too much ugly white space
684 PunctWordLength < Columns/3)
685 return End; // Take the whole thing as a single "word".
686
687 // The whole quoted/parenthesized string is too long to print as a
688 // single "word". Instead, find the "word" that starts just after
689 // the punctuation and use that end-point instead. This will recurse
690 // until it finds something small enough to consider a word.
691 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
692}
693
694/// \brief Print the given string to a stream, word-wrapping it to
695/// some number of columns in the process.
696///
697/// \brief OS the stream to which the word-wrapping string will be
698/// emitted.
699///
700/// \brief Str the string to word-wrap and output.
701///
702/// \brief Columns the number of columns to word-wrap to.
703///
704/// \brief Column the column number at which the first character of \p
705/// Str will be printed. This will be non-zero when part of the first
706/// line has already been printed.
707///
708/// \brief Indentation the number of spaces to indent any lines beyond
709/// the first line.
710///
711/// \returns true if word-wrapping was required, or false if the
712/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000713static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000714 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000715 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000716 unsigned Column = 0,
717 unsigned Indentation = WordWrapIndentation) {
718 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000719
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000720 // If there is a newline in this message somewhere, find that
721 // newline and split the message into the part before the newline
722 // (which will be word-wrapped) and the part from the newline one
723 // (which will be emitted unchanged).
724 for (unsigned I = 0; I != Length; ++I)
725 if (Str[I] == '\n') {
726 Length = I;
727 break;
728 }
729
730 // The string used to indent each line.
731 llvm::SmallString<16> IndentStr;
732 IndentStr.assign(Indentation, ' ');
733 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000734 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000735 WordStart = WordEnd) {
736 // Find the beginning of the next word.
737 WordStart = skipWhitespace(WordStart, Str, Length);
738 if (WordStart == Length)
739 break;
740
741 // Find the end of this word.
742 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000743
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000744 // Does this word fit on the current line?
745 unsigned WordLength = WordEnd - WordStart;
746 if (Column + WordLength < Columns) {
747 // This word fits on the current line; print it there.
748 if (WordStart) {
749 OS << ' ';
750 Column += 1;
751 }
752 OS.write(&Str[WordStart], WordLength);
753 Column += WordLength;
754 continue;
755 }
756
757 // This word does not fit on the current line, so wrap to the next
758 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000759 OS << '\n';
760 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000761 OS.write(&Str[WordStart], WordLength);
762 Column = Indentation + WordLength;
763 Wrapped = true;
764 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000765
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000766 if (Length == Str.size())
767 return Wrapped; // We're done.
768
769 // There is a newline in the message, followed by something that
770 // will not be word-wrapped. Print that.
771 OS.write(&Str[Length], Str.size() - Length);
772 return true;
773}
Chris Lattner94f55782009-02-17 07:38:37 +0000774
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000775void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000776 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000777 // Default implementation (Warnings/errors count).
778 DiagnosticClient::HandleDiagnostic(Level, Info);
779
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000780 // Keeps track of the the starting position of the location
781 // information (e.g., "foo.c:10:4:") that precedes the error
782 // message. We use this information to determine how long the
783 // file+line+column number prefix is.
784 uint64_t StartOfLocationInfo = OS.tell();
785
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000786 if (!Prefix.empty())
787 OS << Prefix << ": ";
788
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000789 // If the location is specified, print out a file/line/col and include trace
790 // if enabled.
791 if (Info.getLocation().isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000792 const SourceManager &SM = Info.getSourceManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000793 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
Axel Naumann04331162011-01-27 10:55:51 +0000794 if (PLoc.isInvalid()) {
795 // At least print the file name if available:
796 FileID FID = SM.getFileID(Info.getLocation());
797 if (!FID.isInvalid()) {
798 const FileEntry* FE = SM.getFileEntryForID(FID);
799 if (FE && FE->getName()) {
800 OS << FE->getName();
801 if (FE->getDevice() == 0 && FE->getInode() == 0
802 && FE->getFileMode() == 0) {
803 // in PCH is a guess, but a good one:
804 OS << " (in PCH)";
805 }
806 OS << ": ";
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000807 }
Axel Naumann04331162011-01-27 10:55:51 +0000808 }
809 } else {
810 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000811
Axel Naumann04331162011-01-27 10:55:51 +0000812 // First, if this diagnostic is not in the main file, print out the
813 // "included from" lines.
814 if (LastWarningLoc != PLoc.getIncludeLoc()) {
815 LastWarningLoc = PLoc.getIncludeLoc();
Chandler Carruthabaca7a2011-03-27 01:50:55 +0000816 PrintIncludeStack(Level, LastWarningLoc, SM);
Axel Naumann04331162011-01-27 10:55:51 +0000817 StartOfLocationInfo = OS.tell();
818 }
819
820 // Compute the column number.
Matt Beaumont-Gay32ad9352011-03-31 01:46:47 +0000821 if (DiagOpts->ShowLocation) {
Axel Naumann04331162011-01-27 10:55:51 +0000822 if (DiagOpts->ShowColors)
823 OS.changeColor(savedColor, true);
824
Douglas Gregorc9471b02011-05-21 17:07:29 +0000825 OS << PLoc.getFilename();
826 switch (DiagOpts->Format) {
827 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
828 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
829 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
Axel Naumann04331162011-01-27 10:55:51 +0000830 }
Douglas Gregorc9471b02011-05-21 17:07:29 +0000831 if (DiagOpts->ShowColumn)
832 if (unsigned ColNo = PLoc.getColumn()) {
833 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
834 OS << ',';
835 ColNo--;
836 } else
837 OS << ':';
838 OS << ColNo;
839 }
840 switch (DiagOpts->Format) {
841 case DiagnosticOptions::Clang:
842 case DiagnosticOptions::Vi: OS << ':'; break;
843 case DiagnosticOptions::Msvc: OS << ") : "; break;
844 }
845
846
Axel Naumann04331162011-01-27 10:55:51 +0000847 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
848 FileID CaretFileID =
849 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
850 bool PrintedRange = false;
851
852 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
853 // Ignore invalid ranges.
854 if (!Info.getRange(i).isValid()) continue;
855
856 SourceLocation B = Info.getRange(i).getBegin();
857 SourceLocation E = Info.getRange(i).getEnd();
858 B = SM.getInstantiationLoc(B);
859 E = SM.getInstantiationLoc(E);
860
861 // If the End location and the start location are the same and are a
862 // macro location, then the range was something that came from a
863 // macro expansion or _Pragma. If this is an object-like macro, the
864 // best we can do is to highlight the range. If this is a
865 // function-like macro, we'd also like to highlight the arguments.
866 if (B == E && Info.getRange(i).getEnd().isMacroID())
867 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
868
869 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
870 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
871
872 // If the start or end of the range is in another file, just discard
873 // it.
874 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
875 continue;
876
877 // Add in the length of the token, so that we cover multi-char
878 // tokens.
879 unsigned TokSize = 0;
880 if (Info.getRange(i).isTokenRange())
881 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
882
883 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
884 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
885 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
886 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
887 << '}';
888 PrintedRange = true;
889 }
890
891 if (PrintedRange)
892 OS << ':';
893 }
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000894 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000895 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000896 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000897 OS.resetColor();
898 }
899 }
900
Daniel Dunbareace8742009-11-04 06:24:30 +0000901 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000902 // Print diagnostic category in bold and color
903 switch (Level) {
904 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
905 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
906 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
907 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
908 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000909 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000911
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000913 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000914 case Diagnostic::Note: OS << "note: "; break;
915 case Diagnostic::Warning: OS << "warning: "; break;
916 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000917 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000918 }
Torok Edwin603fca72009-06-04 07:18:23 +0000919
Daniel Dunbareace8742009-11-04 06:24:30 +0000920 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000921 OS.resetColor();
922
Chris Lattnerf4c83962008-11-19 06:51:40 +0000923 llvm::SmallString<100> OutStr;
924 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000925
Douglas Gregor7d2b8c12011-04-15 22:04:17 +0000926 if (DiagOpts->ShowNames &&
927 !DiagnosticIDs::isBuiltinNote(Info.getID())) {
928 OutStr += " [";
929 OutStr += DiagnosticIDs::getName(Info.getID());
930 OutStr += "]";
931 }
932
Chris Lattnerc9b88902010-05-04 21:13:21 +0000933 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000934 if (DiagOpts->ShowOptionNames) {
Ted Kremenek7decebf2011-02-25 01:28:26 +0000935 // Was this a warning mapped to an error using -Werror or pragma?
936 if (Level == Diagnostic::Error &&
937 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
938 diag::Mapping mapping = diag::MAP_IGNORE;
939 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
940 &mapping);
941 if (mapping == diag::MAP_WARNING)
942 OptionName += "-Werror";
943 }
944
Argyrios Kyrtzidis477aab62011-05-25 05:05:01 +0000945 llvm::StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
946 if (!Opt.empty()) {
Ted Kremenek7decebf2011-02-25 01:28:26 +0000947 if (!OptionName.empty())
948 OptionName += ',';
949 OptionName += "-W";
Chris Lattnerc9b88902010-05-04 21:13:21 +0000950 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +0000951 } else if (Info.getID() == diag::fatal_too_many_errors) {
952 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +0000953 } else {
954 // If the diagnostic is an extension diagnostic and not enabled by default
955 // then it must have been turned on with -pedantic.
956 bool EnabledByDefault;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000957 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
958 EnabledByDefault) &&
Chris Lattner04e44272010-04-12 21:53:11 +0000959 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000960 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000961 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000962 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000963
964 // If the user wants to see category information, include it too.
965 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +0000966 if (DiagOpts->ShowCategories)
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000967 DiagCategory = DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000968
Chris Lattnerc9b88902010-05-04 21:13:21 +0000969 // If there is any categorization information, include it.
970 if (!OptionName.empty() || DiagCategory != 0) {
971 bool NeedsComma = false;
972 OutStr += " [";
973
974 if (!OptionName.empty()) {
975 OutStr += OptionName;
976 NeedsComma = true;
977 }
978
979 if (DiagCategory) {
980 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +0000981 if (DiagOpts->ShowCategories == 1)
982 OutStr += llvm::utostr(DiagCategory);
983 else {
984 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000985 OutStr += DiagnosticIDs::getCategoryNameFromID(DiagCategory);
Chris Lattner6fbe8392010-05-04 21:55:25 +0000986 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000987 }
988
989 OutStr += "]";
990 }
991
992
Daniel Dunbareace8742009-11-04 06:24:30 +0000993 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000994 // Print warnings, errors and fatal errors in bold, no color
995 switch (Level) {
996 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
997 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
998 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
999 default: break; //don't bold notes
1000 }
1001 }
1002
Daniel Dunbareace8742009-11-04 06:24:30 +00001003 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001004 // We will be word-wrapping the error message, so compute the
1005 // column number where we currently are (after printing the
1006 // location information).
1007 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +00001008 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +00001009 } else {
1010 OS.write(OutStr.begin(), OutStr.size());
1011 }
Chris Lattnerf4c83962008-11-19 06:51:40 +00001012 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +00001013 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +00001014 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001015
Douglas Gregordf667e72009-03-10 20:44:00 +00001016 // If caret diagnostics are enabled and we have location, we want to
1017 // emit the caret. However, we only do this if the location moved
1018 // from the last diagnostic, if the last diagnostic was a note that
1019 // was part of a different warning or error diagnostic, or if the
1020 // diagnostic has ranges. We don't want to emit the same caret
1021 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +00001022 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001023 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +00001024 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001025 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001026 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001027 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Douglas Gregordf667e72009-03-10 20:44:00 +00001028 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001029
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001030 // Get the ranges into a local array we can hack on.
Chris Lattner0a76aae2010-06-18 22:45:06 +00001031 CharSourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001032 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001033 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001034 for (unsigned i = 0; i != NumRanges; ++i)
1035 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001036
Douglas Gregor849b2432010-03-31 17:46:05 +00001037 unsigned NumHints = Info.getNumFixItHints();
Chris Lattner0a76aae2010-06-18 22:45:06 +00001038 for (unsigned i = 0; i != NumHints; ++i) {
1039 const FixItHint &Hint = Info.getFixItHint(i);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001040 if (Hint.RemoveRange.isValid()) {
1041 assert(NumRanges < 20 && "Out of space");
1042 Ranges[NumRanges++] = Hint.RemoveRange;
1043 }
1044 }
1045
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001046 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
1047 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
1048 // Compute the length of the macro-instantiation backtrace, so that we
1049 // can establish which steps in the macro backtrace we'll skip.
1050 SourceLocation Loc = LastLoc;
1051 unsigned Depth = 0;
1052 do {
1053 ++Depth;
1054 Loc = LastLoc.getManager().getImmediateInstantiationRange(Loc).first;
1055 } while (!Loc.isFileID());
1056
1057 if (Depth > DiagOpts->MacroBacktraceLimit) {
1058 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
1059 DiagOpts->MacroBacktraceLimit % 2;
1060 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
1061 }
1062 }
1063
Chris Lattner83068312011-06-28 05:11:33 +00001064 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +00001065 Info.getFixItHints(),
1066 Info.getNumFixItHints(),
Douglas Gregor6c1cb992010-05-04 17:13:42 +00001067 DiagOpts->MessageLength,
1068 0, MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001070
Chris Lattnera03a5b52008-11-19 06:56:25 +00001071 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001072}