blob: 547ff4d46b7c06d4be5e63b7c3fd86e8fe9b0757 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/Basic/SourceManager.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000016#include "clang/Frontend/DiagnosticOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Lex/Lexer.h"
Chris Lattner037fb7f2009-05-05 22:03:18 +000018#include "llvm/Support/MemoryBuffer.h"
Chris Lattnera03a5b52008-11-19 06:56:25 +000019#include "llvm/Support/raw_ostream.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000020#include "llvm/ADT/SmallString.h"
Chris Lattnerc9b88902010-05-04 21:13:21 +000021#include "llvm/ADT/StringExtras.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000022#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24
Torok Edwin603fca72009-06-04 07:18:23 +000025static const enum llvm::raw_ostream::Colors noteColor =
26 llvm::raw_ostream::BLACK;
27static const enum llvm::raw_ostream::Colors fixitColor =
28 llvm::raw_ostream::GREEN;
29static const enum llvm::raw_ostream::Colors caretColor =
30 llvm::raw_ostream::GREEN;
31static const enum llvm::raw_ostream::Colors warningColor =
32 llvm::raw_ostream::MAGENTA;
33static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
34static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000035// Used for changing only the bold attribute.
Torok Edwin603fca72009-06-04 07:18:23 +000036static const enum llvm::raw_ostream::Colors savedColor =
37 llvm::raw_ostream::SAVEDCOLOR;
38
Douglas Gregorfffd93f2009-05-01 21:53:04 +000039/// \brief Number of spaces to indent when word-wrapping.
40const unsigned WordWrapIndentation = 6;
41
Daniel Dunbareace8742009-11-04 06:24:30 +000042TextDiagnosticPrinter::TextDiagnosticPrinter(llvm::raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000043 const DiagnosticOptions &diags,
44 bool _OwnsOutputStream)
Daniel Dunbareace8742009-11-04 06:24:30 +000045 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbaraea36412009-11-11 09:38:24 +000046 LastCaretDiagnosticWasNote(0),
47 OwnsOutputStream(_OwnsOutputStream) {
48}
49
50TextDiagnosticPrinter::~TextDiagnosticPrinter() {
51 if (OwnsOutputStream)
52 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000053}
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055void TextDiagnosticPrinter::
Chris Lattnerb9c3f962009-01-27 07:57:44 +000056PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
57 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000058
Chris Lattnerb9c3f962009-01-27 07:57:44 +000059 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner9dc1f532007-07-20 16:37:10 +000060
Reid Spencer5f016e22007-07-11 17:01:13 +000061 // Print out the other include frames first.
Chris Lattnerb9c3f962009-01-27 07:57:44 +000062 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000063
Daniel Dunbareace8742009-11-04 06:24:30 +000064 if (DiagOpts->ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000065 OS << "In file included from " << PLoc.getFilename()
66 << ':' << PLoc.getLine() << ":\n";
67 else
68 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000069}
70
71/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
72/// any characters in LineNo that intersect the SourceRange.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000073void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000074 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000075 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000076 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000077 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000078 assert(CaretLine.size() == SourceLine.size() &&
79 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000080 if (!R.isValid()) return;
81
Chris Lattnerb9c3f962009-01-27 07:57:44 +000082 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
83 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000084
Chris Lattner34837a52009-02-17 05:19:10 +000085 // If the End location and the start location are the same and are a macro
86 // location, then the range was something that came from a macro expansion
87 // or _Pragma. If this is an object-like macro, the best we can do is to
88 // highlight the range. If this is a function-like macro, we'd also like to
89 // highlight the arguments.
90 if (Begin == End && R.getEnd().isMacroID())
91 End = SM.getInstantiationRange(R.getEnd()).second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000092
Chris Lattner30fc9332009-02-04 01:06:56 +000093 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000094 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000095 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000096
Chris Lattner30fc9332009-02-04 01:06:56 +000097 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000098 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000099 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000100
Reid Spencer5f016e22007-07-11 17:01:13 +0000101 // Compute the column number of the start.
102 unsigned StartColNo = 0;
103 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000104 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 if (StartColNo) --StartColNo; // Zero base the col #.
106 }
107
Reid Spencer5f016e22007-07-11 17:01:13 +0000108 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +0000109 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000111 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 if (EndColNo) {
113 --EndColNo; // Zero base the col #.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000114
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000116 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000117 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000118 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 }
120 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000121
Chris Lattner41e79e22010-02-12 18:52:52 +0000122 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000123
Chris Lattner41e79e22010-02-12 18:52:52 +0000124 // Pick the first non-whitespace column.
125 while (StartColNo < SourceLine.size() &&
126 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
127 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 // Pick the last non-whitespace column.
Chris Lattner41e79e22010-02-12 18:52:52 +0000130 if (EndColNo > SourceLine.size())
Nuno Lopesdb825682008-08-05 19:40:20 +0000131 EndColNo = SourceLine.size();
Chris Lattner41e79e22010-02-12 18:52:52 +0000132 while (EndColNo-1 &&
133 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
134 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000135
Chris Lattner41e79e22010-02-12 18:52:52 +0000136 // If the start/end passed each other, then we are trying to highlight a range
137 // that just exists in whitespace, which must be some sort of other bug.
138 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000141 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000142 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000143}
144
Douglas Gregor47f71772009-05-01 23:32:58 +0000145/// \brief When the source code line we want to print is too long for
146/// the terminal, select the "interesting" region.
147static void SelectInterestingSourceRegion(std::string &SourceLine,
148 std::string &CaretLine,
149 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000150 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000151 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000152 unsigned MaxSize = std::max(SourceLine.size(),
153 std::max(CaretLine.size(),
154 FixItInsertionLine.size()));
155 if (MaxSize > SourceLine.size())
156 SourceLine.resize(MaxSize, ' ');
157 if (MaxSize > CaretLine.size())
158 CaretLine.resize(MaxSize, ' ');
159 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
160 FixItInsertionLine.resize(MaxSize, ' ');
161
Douglas Gregor47f71772009-05-01 23:32:58 +0000162 // Find the slice that we need to display the full caret line
163 // correctly.
164 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
165 for (; CaretStart != CaretEnd; ++CaretStart)
166 if (!isspace(CaretLine[CaretStart]))
167 break;
168
169 for (; CaretEnd != CaretStart; --CaretEnd)
170 if (!isspace(CaretLine[CaretEnd - 1]))
171 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000172
173 // Make sure we don't chop the string shorter than the caret token
174 // itself.
175 if (CaretEnd < EndOfCaretToken)
176 CaretEnd = EndOfCaretToken;
177
Douglas Gregor844da342009-05-03 04:33:32 +0000178 // If we have a fix-it line, make sure the slice includes all of the
179 // fix-it information.
180 if (!FixItInsertionLine.empty()) {
181 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
182 for (; FixItStart != FixItEnd; ++FixItStart)
183 if (!isspace(FixItInsertionLine[FixItStart]))
184 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000185
Douglas Gregor844da342009-05-03 04:33:32 +0000186 for (; FixItEnd != FixItStart; --FixItEnd)
187 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
188 break;
189
190 if (FixItStart < CaretStart)
191 CaretStart = FixItStart;
192 if (FixItEnd > CaretEnd)
193 CaretEnd = FixItEnd;
194 }
195
Douglas Gregor47f71772009-05-01 23:32:58 +0000196 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
197 // parts of the caret line. While this slice is smaller than the
198 // number of columns we have, try to grow the slice to encompass
199 // more context.
200
201 // If the end of the interesting region comes before we run out of
202 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000203 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000204 CaretStart = 0;
205
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000206 unsigned TargetColumns = Columns;
207 if (TargetColumns > 8)
208 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000209 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000210 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000211 bool ExpandedRegion = false;
212 // Move the start of the interesting region left until we've
213 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000214 if (CaretStart == 1)
215 CaretStart = 0;
216 else if (CaretStart > 1) {
217 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000218
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000219 // Skip over any whitespace we see here; we're looking for
220 // another bit of interesting text.
221 while (NewStart && isspace(SourceLine[NewStart]))
222 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000223
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000224 // Skip over this bit of "interesting" text.
225 while (NewStart && !isspace(SourceLine[NewStart]))
226 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000227
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000228 // Move up to the non-whitespace character we just saw.
229 if (NewStart)
230 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000231
232 // If we're still within our limit, update the starting
233 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000234 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000235 CaretStart = NewStart;
236 ExpandedRegion = true;
237 }
238 }
239
240 // Move the end of the interesting region right until we've
241 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000242 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000243 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000244 unsigned NewEnd = CaretEnd;
245
246 // Skip over any whitespace we see here; we're looking for
247 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000248 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000249 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000250
Douglas Gregor47f71772009-05-01 23:32:58 +0000251 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000252 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000253 ++NewEnd;
254
255 if (NewEnd - CaretStart <= TargetColumns) {
256 CaretEnd = NewEnd;
257 ExpandedRegion = true;
258 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000259 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000260
261 if (!ExpandedRegion)
262 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000263 }
264
265 // [CaretStart, CaretEnd) is the slice we want. Update the various
266 // output lines to show only this slice, with two-space padding
267 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000268 if (CaretEnd < SourceLine.size())
269 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000270 if (CaretEnd < CaretLine.size())
271 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000272 if (FixItInsertionLine.size() > CaretEnd)
273 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000274
Douglas Gregor47f71772009-05-01 23:32:58 +0000275 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000276 SourceLine.replace(0, CaretStart, " ...");
277 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000278 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000279 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000280 }
281}
282
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000283void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner676f0242009-02-20 00:25:28 +0000284 SourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000285 unsigned NumRanges,
Chris Lattner5c5db4e2010-04-20 20:49:23 +0000286 const SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000287 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000288 unsigned NumHints,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000289 unsigned Columns,
290 unsigned OnMacroInst,
291 unsigned MacroSkipStart,
292 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000293 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000294 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000295
296 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000297 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000298 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000299 if (!Loc.isFileID()) {
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000300 // Whether to suppress printing this macro instantiation.
301 bool Suppressed
302 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
303
304
Chris Lattner609b3ab2009-02-18 18:50:45 +0000305 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000306 // FIXME: Map ranges?
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000307 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns,
308 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
309
Chris Lattner2e77aa12009-12-04 07:06:35 +0000310 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000311 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000312
Chris Lattner676f0242009-02-20 00:25:28 +0000313 // Map the ranges.
314 for (unsigned i = 0; i != NumRanges; ++i) {
315 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000316 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
317 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000318 Ranges[i] = SourceRange(S, E);
319 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000320
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000321 if (!Suppressed) {
322 // Get the pretty name, according to #line directives etc.
323 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000324
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000325 // If this diagnostic is not in the main file, print out the
326 // "included from" lines.
327 if (LastWarningLoc != PLoc.getIncludeLoc()) {
328 LastWarningLoc = PLoc.getIncludeLoc();
329 PrintIncludeStack(LastWarningLoc, SM);
330 }
331
332 if (DiagOpts->ShowLocation) {
333 // Emit the file/line/column that this expansion came from.
334 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
335 if (DiagOpts->ShowColumn)
336 OS << PLoc.getColumn() << ':';
337 OS << ' ';
338 }
339 OS << "note: instantiated from:\n";
340
341 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns,
342 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
343 return;
Chris Lattner2e77aa12009-12-04 07:06:35 +0000344 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000345
346 if (OnMacroInst == MacroSkipStart) {
347 // Tell the user that we've skipped contexts.
348 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
349 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see "
350 "all)\n";
Chris Lattner5ce24c82009-04-21 03:57:54 +0000351 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000352
Chris Lattner037fb7f2009-05-05 22:03:18 +0000353 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000354 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000355
Chris Lattnerb88af812009-02-17 07:51:53 +0000356 // Decompose the location into a FID/Offset pair.
357 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
358 FileID FID = LocInfo.first;
359 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000360
Chris Lattnerb88af812009-02-17 07:51:53 +0000361 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000362 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000363 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000364 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000365 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000366
Chris Lattnerb88af812009-02-17 07:51:53 +0000367 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000368 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000369 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
370
Chris Lattner94f55782009-02-17 07:38:37 +0000371 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000372 const char *TokPtr = BufStart+FileOffset;
373 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000374
375
Chris Lattner94f55782009-02-17 07:38:37 +0000376 // Compute the line end. Scan forward from the error position to the end of
377 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000378 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000379 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000380 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000381
Daniel Dunbar06d10722009-10-19 09:11:21 +0000382 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
383 // the source line length as currently being computed. See
384 // test/Misc/message-length.c.
385 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
386
Chris Lattner94f55782009-02-17 07:38:37 +0000387 // Copy the line of code into an std::string for ease of manipulation.
388 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000389
Chris Lattner94f55782009-02-17 07:38:37 +0000390 // Create a line for the caret that is filled with spaces that is the same
391 // length as the line of source code.
392 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000393
Chris Lattner94f55782009-02-17 07:38:37 +0000394 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000395 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000396 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000397
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000398 for (unsigned i = 0, e = NumRanges; i != e; ++i)
399 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000400 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000401
Chris Lattner94f55782009-02-17 07:38:37 +0000402 // Next, insert the caret itself.
403 if (ColNo-1 < CaretLine.size())
404 CaretLine[ColNo-1] = '^';
405 else
406 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000407
Chris Lattner94f55782009-02-17 07:38:37 +0000408 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000409 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000410 for (unsigned i = 0; i != SourceLine.size(); ++i) {
411 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000412
Chris Lattner94f55782009-02-17 07:38:37 +0000413 // Replace this tab with at least one space.
414 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000415
Chris Lattner94f55782009-02-17 07:38:37 +0000416 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000417 unsigned TabStop = DiagOpts->TabStop;
418 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
419 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000420 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
421 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000422
Chris Lattner94f55782009-02-17 07:38:37 +0000423 // Insert spaces into the SourceLine.
424 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000425
Chris Lattner94f55782009-02-17 07:38:37 +0000426 // Insert spaces or ~'s into CaretLine.
427 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
428 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000429
Chris Lattner770dbf02009-04-28 22:33:16 +0000430 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
431 // produce easily machine parsable output. Add a space before the source line
432 // and the caret to make it trivial to tell the main diagnostic line from what
433 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000434 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000435 SourceLine = ' ' + SourceLine;
436 CaretLine = ' ' + CaretLine;
437 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000438
Douglas Gregor47f71772009-05-01 23:32:58 +0000439 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000440 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000441 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000442 Hint != LastHint; ++Hint) {
443 if (Hint->InsertionLoc.isValid()) {
444 // We have an insertion hint. Determine whether the inserted
445 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000446 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000447 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000448 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
449 SM.getLineNumber(FID, FileOffset)) {
450 // Insert the new code into the line just below the code
451 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000452 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000453 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000454 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000455 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000456 if (LastColumnModified > FixItInsertionLine.size())
457 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000458 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000459 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000460 } else {
461 FixItInsertionLine.clear();
462 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000463 }
464 }
465 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000466 // Now that we have the entire fixit line, expand the tabs in it.
467 // Since we don't want to insert spaces in the middle of a word,
468 // find each word and the column it should line up with and insert
469 // spaces until they match.
470 if (!FixItInsertionLine.empty()) {
471 unsigned FixItPos = 0;
472 unsigned LinePos = 0;
473 unsigned TabExpandedCol = 0;
474 unsigned LineLength = LineEnd - LineStart;
475
476 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
477 // Find the next word in the FixIt line.
478 while (FixItPos < FixItInsertionLine.size() &&
479 FixItInsertionLine[FixItPos] == ' ')
480 ++FixItPos;
481 unsigned CharDistance = FixItPos - TabExpandedCol;
482
483 // Walk forward in the source line, keeping track of
484 // the tab-expanded column.
485 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
486 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
487 ++TabExpandedCol;
488 else
489 TabExpandedCol =
490 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
491
492 // Adjust the fixit line to match this column.
493 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
494 FixItPos = TabExpandedCol;
495
496 // Walk to the end of the word.
497 while (FixItPos < FixItInsertionLine.size() &&
498 FixItInsertionLine[FixItPos] != ' ')
499 ++FixItPos;
500 }
501 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000502 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000503
Douglas Gregor47f71772009-05-01 23:32:58 +0000504 // If the source line is too long for our terminal, select only the
505 // "interesting" source region within that line.
506 if (Columns && SourceLine.size() > Columns)
507 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000508 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000509
Douglas Gregor47f71772009-05-01 23:32:58 +0000510 // Finally, remove any blank spaces from the end of CaretLine.
511 while (CaretLine[CaretLine.size()-1] == ' ')
512 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000513
Douglas Gregor47f71772009-05-01 23:32:58 +0000514 // Emit what we have computed.
515 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000516
Daniel Dunbareace8742009-11-04 06:24:30 +0000517 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000518 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000519 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000520 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000521 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000522
523 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000524 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000525 // Print fixit line in color
526 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000527 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000528 OS << ' ';
529 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000530 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000531 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000532 }
Chris Lattner94f55782009-02-17 07:38:37 +0000533}
534
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000535/// \brief Skip over whitespace in the string, starting at the given
536/// index.
537///
538/// \returns The index of the first non-whitespace character that is
539/// greater than or equal to Idx or, if no such character exists,
540/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000541static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000542 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000543 unsigned Length) {
544 while (Idx < Length && isspace(Str[Idx]))
545 ++Idx;
546 return Idx;
547}
548
549/// \brief If the given character is the start of some kind of
550/// balanced punctuation (e.g., quotes or parentheses), return the
551/// character that will terminate the punctuation.
552///
553/// \returns The ending punctuation character, if any, or the NULL
554/// character if the input character does not start any punctuation.
555static inline char findMatchingPunctuation(char c) {
556 switch (c) {
557 case '\'': return '\'';
558 case '`': return '\'';
559 case '"': return '"';
560 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000561 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000562 case '{': return '}';
563 default: break;
564 }
565
566 return 0;
567}
568
569/// \brief Find the end of the word starting at the given offset
570/// within a string.
571///
572/// \returns the index pointing one character past the end of the
573/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000574static unsigned findEndOfWord(unsigned Start,
575 const llvm::SmallVectorImpl<char> &Str,
576 unsigned Length, unsigned Column,
577 unsigned Columns) {
578 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000579 unsigned End = Start + 1;
580
Daniel Dunbareae18f82009-12-06 09:56:18 +0000581 // If we are already at the end of the string, take that as the word.
582 if (End == Str.size())
583 return End;
584
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000585 // Determine if the start of the string is actually opening
586 // punctuation, e.g., a quote or parentheses.
587 char EndPunct = findMatchingPunctuation(Str[Start]);
588 if (!EndPunct) {
589 // This is a normal word. Just find the first space character.
590 while (End < Length && !isspace(Str[End]))
591 ++End;
592 return End;
593 }
594
595 // We have the start of a balanced punctuation sequence (quotes,
596 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000597 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000598 PunctuationEndStack.push_back(EndPunct);
599 while (End < Length && !PunctuationEndStack.empty()) {
600 if (Str[End] == PunctuationEndStack.back())
601 PunctuationEndStack.pop_back();
602 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
603 PunctuationEndStack.push_back(SubEndPunct);
604
605 ++End;
606 }
607
608 // Find the first space character after the punctuation ended.
609 while (End < Length && !isspace(Str[End]))
610 ++End;
611
612 unsigned PunctWordLength = End - Start;
613 if (// If the word fits on this line
614 Column + PunctWordLength <= Columns ||
615 // ... or the word is "short enough" to take up the next line
616 // without too much ugly white space
617 PunctWordLength < Columns/3)
618 return End; // Take the whole thing as a single "word".
619
620 // The whole quoted/parenthesized string is too long to print as a
621 // single "word". Instead, find the "word" that starts just after
622 // the punctuation and use that end-point instead. This will recurse
623 // until it finds something small enough to consider a word.
624 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
625}
626
627/// \brief Print the given string to a stream, word-wrapping it to
628/// some number of columns in the process.
629///
630/// \brief OS the stream to which the word-wrapping string will be
631/// emitted.
632///
633/// \brief Str the string to word-wrap and output.
634///
635/// \brief Columns the number of columns to word-wrap to.
636///
637/// \brief Column the column number at which the first character of \p
638/// Str will be printed. This will be non-zero when part of the first
639/// line has already been printed.
640///
641/// \brief Indentation the number of spaces to indent any lines beyond
642/// the first line.
643///
644/// \returns true if word-wrapping was required, or false if the
645/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000646static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000647 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000648 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000649 unsigned Column = 0,
650 unsigned Indentation = WordWrapIndentation) {
651 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000652
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000653 // If there is a newline in this message somewhere, find that
654 // newline and split the message into the part before the newline
655 // (which will be word-wrapped) and the part from the newline one
656 // (which will be emitted unchanged).
657 for (unsigned I = 0; I != Length; ++I)
658 if (Str[I] == '\n') {
659 Length = I;
660 break;
661 }
662
663 // The string used to indent each line.
664 llvm::SmallString<16> IndentStr;
665 IndentStr.assign(Indentation, ' ');
666 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000667 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000668 WordStart = WordEnd) {
669 // Find the beginning of the next word.
670 WordStart = skipWhitespace(WordStart, Str, Length);
671 if (WordStart == Length)
672 break;
673
674 // Find the end of this word.
675 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000676
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000677 // Does this word fit on the current line?
678 unsigned WordLength = WordEnd - WordStart;
679 if (Column + WordLength < Columns) {
680 // This word fits on the current line; print it there.
681 if (WordStart) {
682 OS << ' ';
683 Column += 1;
684 }
685 OS.write(&Str[WordStart], WordLength);
686 Column += WordLength;
687 continue;
688 }
689
690 // This word does not fit on the current line, so wrap to the next
691 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000692 OS << '\n';
693 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000694 OS.write(&Str[WordStart], WordLength);
695 Column = Indentation + WordLength;
696 Wrapped = true;
697 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000698
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000699 if (Length == Str.size())
700 return Wrapped; // We're done.
701
702 // There is a newline in the message, followed by something that
703 // will not be word-wrapped. Print that.
704 OS.write(&Str[Length], Str.size() - Length);
705 return true;
706}
Chris Lattner94f55782009-02-17 07:38:37 +0000707
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000708void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000709 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000710 // Keeps track of the the starting position of the location
711 // information (e.g., "foo.c:10:4:") that precedes the error
712 // message. We use this information to determine how long the
713 // file+line+column number prefix is.
714 uint64_t StartOfLocationInfo = OS.tell();
715
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000716 if (!Prefix.empty())
717 OS << Prefix << ": ";
718
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000719 // If the location is specified, print out a file/line/col and include trace
720 // if enabled.
721 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000722 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000723 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
724 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000725
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // First, if this diagnostic is not in the main file, print out the
727 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000728 if (LastWarningLoc != PLoc.getIncludeLoc()) {
729 LastWarningLoc = PLoc.getIncludeLoc();
730 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000731 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000733
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000734 // Compute the column number.
Daniel Dunbareace8742009-11-04 06:24:30 +0000735 if (DiagOpts->ShowLocation) {
736 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000737 OS.changeColor(savedColor, true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000738
Steve Naroffe0c4d892009-12-05 02:14:08 +0000739 // Emit a Visual Studio compatible line number syntax.
Steve Naroff0304c6c2009-12-05 12:23:07 +0000740 if (LangOpts && LangOpts->Microsoft) {
Steve Naroffe0c4d892009-12-05 02:14:08 +0000741 OS << PLoc.getFilename() << '(' << LineNo << ')';
742 OS << " : ";
743 } else {
744 OS << PLoc.getFilename() << ':' << LineNo << ':';
745 if (DiagOpts->ShowColumn)
746 if (unsigned ColNo = PLoc.getColumn())
747 OS << ColNo << ':';
748 }
Daniel Dunbareace8742009-11-04 06:24:30 +0000749 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000750 FileID CaretFileID =
751 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
752 bool PrintedRange = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000753
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000754 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000755 // Ignore invalid ranges.
756 if (!Info.getRange(i).isValid()) continue;
757
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000758 SourceLocation B = Info.getRange(i).getBegin();
759 SourceLocation E = Info.getRange(i).getEnd();
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000760 B = SM.getInstantiationLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000761 E = SM.getInstantiationLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000762
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000763 // If the End location and the start location are the same and are a
764 // macro location, then the range was something that came from a macro
765 // expansion or _Pragma. If this is an object-like macro, the best we
766 // can do is to highlight the range. If this is a function-like
767 // macro, we'd also like to highlight the arguments.
768 if (B == E && Info.getRange(i).getEnd().isMacroID())
769 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
770
771 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000772 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000773
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000774 // If the start or end of the range is in another file, just discard
775 // it.
776 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
777 continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000778
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000779 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000780 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000781
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000782 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
783 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
784 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
785 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
786 PrintedRange = true;
787 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000788
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000789 if (PrintedRange)
790 OS << ':';
791 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000792 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000793 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000794 OS.resetColor();
795 }
796 }
797
Daniel Dunbareace8742009-11-04 06:24:30 +0000798 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000799 // Print diagnostic category in bold and color
800 switch (Level) {
801 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
802 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
803 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
804 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
805 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000806 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000807 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000808
Reid Spencer5f016e22007-07-11 17:01:13 +0000809 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000810 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000811 case Diagnostic::Note: OS << "note: "; break;
812 case Diagnostic::Warning: OS << "warning: "; break;
813 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000814 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 }
Torok Edwin603fca72009-06-04 07:18:23 +0000816
Daniel Dunbareace8742009-11-04 06:24:30 +0000817 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000818 OS.resetColor();
819
Chris Lattnerf4c83962008-11-19 06:51:40 +0000820 llvm::SmallString<100> OutStr;
821 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000822
Chris Lattnerc9b88902010-05-04 21:13:21 +0000823 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000824 if (DiagOpts->ShowOptionNames) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000825 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
Chris Lattnerc9b88902010-05-04 21:13:21 +0000826 OptionName = "-W";
827 OptionName += Opt;
Chris Lattner04e44272010-04-12 21:53:11 +0000828 } else {
829 // If the diagnostic is an extension diagnostic and not enabled by default
830 // then it must have been turned on with -pedantic.
831 bool EnabledByDefault;
832 if (Diagnostic::isBuiltinExtensionDiag(Info.getID(), EnabledByDefault) &&
833 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000834 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000835 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000836 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000837
838 // If the user wants to see category information, include it too.
839 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +0000840 if (DiagOpts->ShowCategories)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000841 DiagCategory = Diagnostic::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000842
Chris Lattnerc9b88902010-05-04 21:13:21 +0000843 // If there is any categorization information, include it.
844 if (!OptionName.empty() || DiagCategory != 0) {
845 bool NeedsComma = false;
846 OutStr += " [";
847
848 if (!OptionName.empty()) {
849 OutStr += OptionName;
850 NeedsComma = true;
851 }
852
853 if (DiagCategory) {
854 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +0000855 if (DiagOpts->ShowCategories == 1)
856 OutStr += llvm::utostr(DiagCategory);
857 else {
858 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
859 OutStr += Diagnostic::getCategoryNameFromID(DiagCategory);
860 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000861 }
862
863 OutStr += "]";
864 }
865
866
Daniel Dunbareace8742009-11-04 06:24:30 +0000867 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000868 // Print warnings, errors and fatal errors in bold, no color
869 switch (Level) {
870 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
871 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
872 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
873 default: break; //don't bold notes
874 }
875 }
876
Daniel Dunbareace8742009-11-04 06:24:30 +0000877 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000878 // We will be word-wrapping the error message, so compute the
879 // column number where we currently are (after printing the
880 // location information).
881 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +0000882 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000883 } else {
884 OS.write(OutStr.begin(), OutStr.size());
885 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000886 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000887 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000888 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000889
Douglas Gregordf667e72009-03-10 20:44:00 +0000890 // If caret diagnostics are enabled and we have location, we want to
891 // emit the caret. However, we only do this if the location moved
892 // from the last diagnostic, if the last diagnostic was a note that
893 // was part of a different warning or error diagnostic, or if the
894 // diagnostic has ranges. We don't want to emit the same caret
895 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +0000896 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000897 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000898 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +0000899 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000900 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000901 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000902 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000903
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000904 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000905 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000906 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000907 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000908 for (unsigned i = 0; i != NumRanges; ++i)
909 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000910
Douglas Gregor849b2432010-03-31 17:46:05 +0000911 unsigned NumHints = Info.getNumFixItHints();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000912 for (unsigned idx = 0; idx < NumHints; ++idx) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000913 const FixItHint &Hint = Info.getFixItHint(idx);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000914 if (Hint.RemoveRange.isValid()) {
915 assert(NumRanges < 20 && "Out of space");
916 Ranges[NumRanges++] = Hint.RemoveRange;
917 }
918 }
919
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000920 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
921 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
922 // Compute the length of the macro-instantiation backtrace, so that we
923 // can establish which steps in the macro backtrace we'll skip.
924 SourceLocation Loc = LastLoc;
925 unsigned Depth = 0;
926 do {
927 ++Depth;
928 Loc = LastLoc.getManager().getImmediateInstantiationRange(Loc).first;
929 } while (!Loc.isFileID());
930
931 if (Depth > DiagOpts->MacroBacktraceLimit) {
932 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
933 DiagOpts->MacroBacktraceLimit % 2;
934 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
935 }
936 }
937
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000938 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000939 Info.getFixItHints(),
940 Info.getNumFixItHints(),
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000941 DiagOpts->MessageLength,
942 0, MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000944
Chris Lattnera03a5b52008-11-19 06:56:25 +0000945 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000946}