blob: 3f1eb82f7efe33a90199ef096a68d5f1d444492f [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.
Chris Lattner0a76aae2010-06-18 22:45:06 +000073void TextDiagnosticPrinter::HighlightRange(const CharSourceRange &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
Chris Lattner0a76aae2010-06-18 22:45:06 +0000115 // Add in the length of the token, so that we cover multi-char tokens if
116 // this is a token range.
117 if (R.isTokenRange())
118 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000120 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000121 }
122 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000123
Chris Lattner41e79e22010-02-12 18:52:52 +0000124 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000125
Chris Lattner41e79e22010-02-12 18:52:52 +0000126 // Pick the first non-whitespace column.
127 while (StartColNo < SourceLine.size() &&
128 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
129 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000130
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 // Pick the last non-whitespace column.
Chris Lattner41e79e22010-02-12 18:52:52 +0000132 if (EndColNo > SourceLine.size())
Nuno Lopesdb825682008-08-05 19:40:20 +0000133 EndColNo = SourceLine.size();
Chris Lattner41e79e22010-02-12 18:52:52 +0000134 while (EndColNo-1 &&
135 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
136 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000137
Chris Lattner41e79e22010-02-12 18:52:52 +0000138 // If the start/end passed each other, then we are trying to highlight a range
139 // that just exists in whitespace, which must be some sort of other bug.
140 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000141
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000143 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000144 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000145}
146
Douglas Gregor47f71772009-05-01 23:32:58 +0000147/// \brief When the source code line we want to print is too long for
148/// the terminal, select the "interesting" region.
149static void SelectInterestingSourceRegion(std::string &SourceLine,
150 std::string &CaretLine,
151 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000152 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000153 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000154 unsigned MaxSize = std::max(SourceLine.size(),
155 std::max(CaretLine.size(),
156 FixItInsertionLine.size()));
157 if (MaxSize > SourceLine.size())
158 SourceLine.resize(MaxSize, ' ');
159 if (MaxSize > CaretLine.size())
160 CaretLine.resize(MaxSize, ' ');
161 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
162 FixItInsertionLine.resize(MaxSize, ' ');
163
Douglas Gregor47f71772009-05-01 23:32:58 +0000164 // Find the slice that we need to display the full caret line
165 // correctly.
166 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
167 for (; CaretStart != CaretEnd; ++CaretStart)
168 if (!isspace(CaretLine[CaretStart]))
169 break;
170
171 for (; CaretEnd != CaretStart; --CaretEnd)
172 if (!isspace(CaretLine[CaretEnd - 1]))
173 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000174
175 // Make sure we don't chop the string shorter than the caret token
176 // itself.
177 if (CaretEnd < EndOfCaretToken)
178 CaretEnd = EndOfCaretToken;
179
Douglas Gregor844da342009-05-03 04:33:32 +0000180 // If we have a fix-it line, make sure the slice includes all of the
181 // fix-it information.
182 if (!FixItInsertionLine.empty()) {
183 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
184 for (; FixItStart != FixItEnd; ++FixItStart)
185 if (!isspace(FixItInsertionLine[FixItStart]))
186 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000187
Douglas Gregor844da342009-05-03 04:33:32 +0000188 for (; FixItEnd != FixItStart; --FixItEnd)
189 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
190 break;
191
192 if (FixItStart < CaretStart)
193 CaretStart = FixItStart;
194 if (FixItEnd > CaretEnd)
195 CaretEnd = FixItEnd;
196 }
197
Douglas Gregor47f71772009-05-01 23:32:58 +0000198 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
199 // parts of the caret line. While this slice is smaller than the
200 // number of columns we have, try to grow the slice to encompass
201 // more context.
202
203 // If the end of the interesting region comes before we run out of
204 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000205 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000206 CaretStart = 0;
207
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000208 unsigned TargetColumns = Columns;
209 if (TargetColumns > 8)
210 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000211 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000212 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000213 bool ExpandedRegion = false;
214 // Move the start of the interesting region left until we've
215 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000216 if (CaretStart == 1)
217 CaretStart = 0;
218 else if (CaretStart > 1) {
219 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000220
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000221 // Skip over any whitespace we see here; we're looking for
222 // another bit of interesting text.
223 while (NewStart && isspace(SourceLine[NewStart]))
224 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000225
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000226 // Skip over this bit of "interesting" text.
227 while (NewStart && !isspace(SourceLine[NewStart]))
228 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000229
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000230 // Move up to the non-whitespace character we just saw.
231 if (NewStart)
232 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000233
234 // If we're still within our limit, update the starting
235 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000236 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000237 CaretStart = NewStart;
238 ExpandedRegion = true;
239 }
240 }
241
242 // Move the end of the interesting region right until we've
243 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000244 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000245 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000246 unsigned NewEnd = CaretEnd;
247
248 // Skip over any whitespace we see here; we're looking for
249 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000250 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000251 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000252
Douglas Gregor47f71772009-05-01 23:32:58 +0000253 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000254 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000255 ++NewEnd;
256
257 if (NewEnd - CaretStart <= TargetColumns) {
258 CaretEnd = NewEnd;
259 ExpandedRegion = true;
260 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000261 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000262
263 if (!ExpandedRegion)
264 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000265 }
266
267 // [CaretStart, CaretEnd) is the slice we want. Update the various
268 // output lines to show only this slice, with two-space padding
269 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000270 if (CaretEnd < SourceLine.size())
271 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000272 if (CaretEnd < CaretLine.size())
273 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000274 if (FixItInsertionLine.size() > CaretEnd)
275 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000276
Douglas Gregor47f71772009-05-01 23:32:58 +0000277 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000278 SourceLine.replace(0, CaretStart, " ...");
279 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000280 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000281 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000282 }
283}
284
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000285void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000286 CharSourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000287 unsigned NumRanges,
Chris Lattner5c5db4e2010-04-20 20:49:23 +0000288 const SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000289 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000290 unsigned NumHints,
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000291 unsigned Columns,
292 unsigned OnMacroInst,
293 unsigned MacroSkipStart,
294 unsigned MacroSkipEnd) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000295 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000296 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000297
298 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000299 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000300 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000301 if (!Loc.isFileID()) {
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000302 // Whether to suppress printing this macro instantiation.
303 bool Suppressed
304 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
305
306
Chris Lattner609b3ab2009-02-18 18:50:45 +0000307 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000308 // FIXME: Map ranges?
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000309 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns,
310 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
311
Chris Lattner2e77aa12009-12-04 07:06:35 +0000312 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000313 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000314
Chris Lattner676f0242009-02-20 00:25:28 +0000315 // Map the ranges.
316 for (unsigned i = 0; i != NumRanges; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +0000317 CharSourceRange &R = Ranges[i];
318 SourceLocation S = R.getBegin(), E = R.getEnd();
319 if (S.isMacroID())
320 R.setBegin(SM.getImmediateSpellingLoc(S));
321 if (E.isMacroID())
322 R.setEnd(SM.getImmediateSpellingLoc(E));
Chris Lattner676f0242009-02-20 00:25:28 +0000323 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000324
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000325 if (!Suppressed) {
326 // Get the pretty name, according to #line directives etc.
327 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000328
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000329 // If this diagnostic is not in the main file, print out the
330 // "included from" lines.
331 if (LastWarningLoc != PLoc.getIncludeLoc()) {
332 LastWarningLoc = PLoc.getIncludeLoc();
333 PrintIncludeStack(LastWarningLoc, SM);
334 }
335
336 if (DiagOpts->ShowLocation) {
337 // Emit the file/line/column that this expansion came from.
338 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
339 if (DiagOpts->ShowColumn)
340 OS << PLoc.getColumn() << ':';
341 OS << ' ';
342 }
343 OS << "note: instantiated from:\n";
344
345 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns,
346 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
347 return;
Chris Lattner2e77aa12009-12-04 07:06:35 +0000348 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000349
350 if (OnMacroInst == MacroSkipStart) {
351 // Tell the user that we've skipped contexts.
352 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
353 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see "
354 "all)\n";
Chris Lattner5ce24c82009-04-21 03:57:54 +0000355 }
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000356
Chris Lattner037fb7f2009-05-05 22:03:18 +0000357 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000358 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000359
Chris Lattnerb88af812009-02-17 07:51:53 +0000360 // Decompose the location into a FID/Offset pair.
361 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
362 FileID FID = LocInfo.first;
363 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000364
Chris Lattnerb88af812009-02-17 07:51:53 +0000365 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000366 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000367 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000368 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000369 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000370
Chris Lattnerb88af812009-02-17 07:51:53 +0000371 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000372 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000373 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
374
Chris Lattner94f55782009-02-17 07:38:37 +0000375 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000376 const char *TokPtr = BufStart+FileOffset;
377 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000378
379
Chris Lattner94f55782009-02-17 07:38:37 +0000380 // Compute the line end. Scan forward from the error position to the end of
381 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000382 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000383 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000384 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000385
Daniel Dunbar06d10722009-10-19 09:11:21 +0000386 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
387 // the source line length as currently being computed. See
388 // test/Misc/message-length.c.
389 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
390
Chris Lattner94f55782009-02-17 07:38:37 +0000391 // Copy the line of code into an std::string for ease of manipulation.
392 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000393
Chris Lattner94f55782009-02-17 07:38:37 +0000394 // Create a line for the caret that is filled with spaces that is the same
395 // length as the line of source code.
396 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000397
Chris Lattner94f55782009-02-17 07:38:37 +0000398 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000399 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000400 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000401
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000402 for (unsigned i = 0, e = NumRanges; i != e; ++i)
403 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000404 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000405
Chris Lattner94f55782009-02-17 07:38:37 +0000406 // Next, insert the caret itself.
407 if (ColNo-1 < CaretLine.size())
408 CaretLine[ColNo-1] = '^';
409 else
410 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000411
Chris Lattner94f55782009-02-17 07:38:37 +0000412 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000413 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000414 for (unsigned i = 0; i != SourceLine.size(); ++i) {
415 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000416
Chris Lattner94f55782009-02-17 07:38:37 +0000417 // Replace this tab with at least one space.
418 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000419
Chris Lattner94f55782009-02-17 07:38:37 +0000420 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000421 unsigned TabStop = DiagOpts->TabStop;
422 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
423 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000424 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
425 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000426
Chris Lattner94f55782009-02-17 07:38:37 +0000427 // Insert spaces into the SourceLine.
428 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000429
Chris Lattner94f55782009-02-17 07:38:37 +0000430 // Insert spaces or ~'s into CaretLine.
431 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
432 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000433
Chris Lattner770dbf02009-04-28 22:33:16 +0000434 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
435 // produce easily machine parsable output. Add a space before the source line
436 // and the caret to make it trivial to tell the main diagnostic line from what
437 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000438 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000439 SourceLine = ' ' + SourceLine;
440 CaretLine = ' ' + CaretLine;
441 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000442
Douglas Gregor47f71772009-05-01 23:32:58 +0000443 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000444 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000445 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000446 Hint != LastHint; ++Hint) {
447 if (Hint->InsertionLoc.isValid()) {
448 // We have an insertion hint. Determine whether the inserted
449 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000450 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000451 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000452 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
453 SM.getLineNumber(FID, FileOffset)) {
454 // Insert the new code into the line just below the code
455 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000456 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000457 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000458 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000459 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000460 if (LastColumnModified > FixItInsertionLine.size())
461 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000462 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000463 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000464 } else {
465 FixItInsertionLine.clear();
466 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000467 }
468 }
469 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000470 // Now that we have the entire fixit line, expand the tabs in it.
471 // Since we don't want to insert spaces in the middle of a word,
472 // find each word and the column it should line up with and insert
473 // spaces until they match.
474 if (!FixItInsertionLine.empty()) {
475 unsigned FixItPos = 0;
476 unsigned LinePos = 0;
477 unsigned TabExpandedCol = 0;
478 unsigned LineLength = LineEnd - LineStart;
479
480 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
481 // Find the next word in the FixIt line.
482 while (FixItPos < FixItInsertionLine.size() &&
483 FixItInsertionLine[FixItPos] == ' ')
484 ++FixItPos;
485 unsigned CharDistance = FixItPos - TabExpandedCol;
486
487 // Walk forward in the source line, keeping track of
488 // the tab-expanded column.
489 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
490 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
491 ++TabExpandedCol;
492 else
493 TabExpandedCol =
494 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
495
496 // Adjust the fixit line to match this column.
497 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
498 FixItPos = TabExpandedCol;
499
500 // Walk to the end of the word.
501 while (FixItPos < FixItInsertionLine.size() &&
502 FixItInsertionLine[FixItPos] != ' ')
503 ++FixItPos;
504 }
505 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000506 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000507
Douglas Gregor47f71772009-05-01 23:32:58 +0000508 // If the source line is too long for our terminal, select only the
509 // "interesting" source region within that line.
510 if (Columns && SourceLine.size() > Columns)
511 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000512 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000513
Douglas Gregor47f71772009-05-01 23:32:58 +0000514 // Finally, remove any blank spaces from the end of CaretLine.
515 while (CaretLine[CaretLine.size()-1] == ' ')
516 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000517
Douglas Gregor47f71772009-05-01 23:32:58 +0000518 // Emit what we have computed.
519 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000520
Daniel Dunbareace8742009-11-04 06:24:30 +0000521 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000522 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000523 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000524 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000525 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000526
527 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000528 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000529 // Print fixit line in color
530 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000531 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000532 OS << ' ';
533 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000534 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000535 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000536 }
Chris Lattner94f55782009-02-17 07:38:37 +0000537}
538
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000539/// \brief Skip over whitespace in the string, starting at the given
540/// index.
541///
542/// \returns The index of the first non-whitespace character that is
543/// greater than or equal to Idx or, if no such character exists,
544/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000545static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000546 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000547 unsigned Length) {
548 while (Idx < Length && isspace(Str[Idx]))
549 ++Idx;
550 return Idx;
551}
552
553/// \brief If the given character is the start of some kind of
554/// balanced punctuation (e.g., quotes or parentheses), return the
555/// character that will terminate the punctuation.
556///
557/// \returns The ending punctuation character, if any, or the NULL
558/// character if the input character does not start any punctuation.
559static inline char findMatchingPunctuation(char c) {
560 switch (c) {
561 case '\'': return '\'';
562 case '`': return '\'';
563 case '"': return '"';
564 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000565 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000566 case '{': return '}';
567 default: break;
568 }
569
570 return 0;
571}
572
573/// \brief Find the end of the word starting at the given offset
574/// within a string.
575///
576/// \returns the index pointing one character past the end of the
577/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000578static unsigned findEndOfWord(unsigned Start,
579 const llvm::SmallVectorImpl<char> &Str,
580 unsigned Length, unsigned Column,
581 unsigned Columns) {
582 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000583 unsigned End = Start + 1;
584
Daniel Dunbareae18f82009-12-06 09:56:18 +0000585 // If we are already at the end of the string, take that as the word.
586 if (End == Str.size())
587 return End;
588
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000589 // Determine if the start of the string is actually opening
590 // punctuation, e.g., a quote or parentheses.
591 char EndPunct = findMatchingPunctuation(Str[Start]);
592 if (!EndPunct) {
593 // This is a normal word. Just find the first space character.
594 while (End < Length && !isspace(Str[End]))
595 ++End;
596 return End;
597 }
598
599 // We have the start of a balanced punctuation sequence (quotes,
600 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000601 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000602 PunctuationEndStack.push_back(EndPunct);
603 while (End < Length && !PunctuationEndStack.empty()) {
604 if (Str[End] == PunctuationEndStack.back())
605 PunctuationEndStack.pop_back();
606 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
607 PunctuationEndStack.push_back(SubEndPunct);
608
609 ++End;
610 }
611
612 // Find the first space character after the punctuation ended.
613 while (End < Length && !isspace(Str[End]))
614 ++End;
615
616 unsigned PunctWordLength = End - Start;
617 if (// If the word fits on this line
618 Column + PunctWordLength <= Columns ||
619 // ... or the word is "short enough" to take up the next line
620 // without too much ugly white space
621 PunctWordLength < Columns/3)
622 return End; // Take the whole thing as a single "word".
623
624 // The whole quoted/parenthesized string is too long to print as a
625 // single "word". Instead, find the "word" that starts just after
626 // the punctuation and use that end-point instead. This will recurse
627 // until it finds something small enough to consider a word.
628 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
629}
630
631/// \brief Print the given string to a stream, word-wrapping it to
632/// some number of columns in the process.
633///
634/// \brief OS the stream to which the word-wrapping string will be
635/// emitted.
636///
637/// \brief Str the string to word-wrap and output.
638///
639/// \brief Columns the number of columns to word-wrap to.
640///
641/// \brief Column the column number at which the first character of \p
642/// Str will be printed. This will be non-zero when part of the first
643/// line has already been printed.
644///
645/// \brief Indentation the number of spaces to indent any lines beyond
646/// the first line.
647///
648/// \returns true if word-wrapping was required, or false if the
649/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000650static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000651 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000652 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000653 unsigned Column = 0,
654 unsigned Indentation = WordWrapIndentation) {
655 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000656
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000657 // If there is a newline in this message somewhere, find that
658 // newline and split the message into the part before the newline
659 // (which will be word-wrapped) and the part from the newline one
660 // (which will be emitted unchanged).
661 for (unsigned I = 0; I != Length; ++I)
662 if (Str[I] == '\n') {
663 Length = I;
664 break;
665 }
666
667 // The string used to indent each line.
668 llvm::SmallString<16> IndentStr;
669 IndentStr.assign(Indentation, ' ');
670 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000671 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000672 WordStart = WordEnd) {
673 // Find the beginning of the next word.
674 WordStart = skipWhitespace(WordStart, Str, Length);
675 if (WordStart == Length)
676 break;
677
678 // Find the end of this word.
679 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000680
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000681 // Does this word fit on the current line?
682 unsigned WordLength = WordEnd - WordStart;
683 if (Column + WordLength < Columns) {
684 // This word fits on the current line; print it there.
685 if (WordStart) {
686 OS << ' ';
687 Column += 1;
688 }
689 OS.write(&Str[WordStart], WordLength);
690 Column += WordLength;
691 continue;
692 }
693
694 // This word does not fit on the current line, so wrap to the next
695 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000696 OS << '\n';
697 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000698 OS.write(&Str[WordStart], WordLength);
699 Column = Indentation + WordLength;
700 Wrapped = true;
701 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000702
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000703 if (Length == Str.size())
704 return Wrapped; // We're done.
705
706 // There is a newline in the message, followed by something that
707 // will not be word-wrapped. Print that.
708 OS.write(&Str[Length], Str.size() - Length);
709 return true;
710}
Chris Lattner94f55782009-02-17 07:38:37 +0000711
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000712void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000713 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000714 // Keeps track of the the starting position of the location
715 // information (e.g., "foo.c:10:4:") that precedes the error
716 // message. We use this information to determine how long the
717 // file+line+column number prefix is.
718 uint64_t StartOfLocationInfo = OS.tell();
719
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000720 if (!Prefix.empty())
721 OS << Prefix << ": ";
722
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000723 // If the location is specified, print out a file/line/col and include trace
724 // if enabled.
725 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000726 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000727 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
728 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000729
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 // First, if this diagnostic is not in the main file, print out the
731 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000732 if (LastWarningLoc != PLoc.getIncludeLoc()) {
733 LastWarningLoc = PLoc.getIncludeLoc();
734 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000735 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000737
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000738 // Compute the column number.
Daniel Dunbareace8742009-11-04 06:24:30 +0000739 if (DiagOpts->ShowLocation) {
740 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000741 OS.changeColor(savedColor, true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000742
Steve Naroffe0c4d892009-12-05 02:14:08 +0000743 // Emit a Visual Studio compatible line number syntax.
Steve Naroff0304c6c2009-12-05 12:23:07 +0000744 if (LangOpts && LangOpts->Microsoft) {
Steve Naroffe0c4d892009-12-05 02:14:08 +0000745 OS << PLoc.getFilename() << '(' << LineNo << ')';
746 OS << " : ";
747 } else {
748 OS << PLoc.getFilename() << ':' << LineNo << ':';
749 if (DiagOpts->ShowColumn)
750 if (unsigned ColNo = PLoc.getColumn())
751 OS << ColNo << ':';
752 }
Daniel Dunbareace8742009-11-04 06:24:30 +0000753 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000754 FileID CaretFileID =
755 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
756 bool PrintedRange = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000757
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000758 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000759 // Ignore invalid ranges.
760 if (!Info.getRange(i).isValid()) continue;
761
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000762 SourceLocation B = Info.getRange(i).getBegin();
763 SourceLocation E = Info.getRange(i).getEnd();
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000764 B = SM.getInstantiationLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000765 E = SM.getInstantiationLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000766
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000767 // If the End location and the start location are the same and are a
768 // macro location, then the range was something that came from a macro
769 // expansion or _Pragma. If this is an object-like macro, the best we
770 // can do is to highlight the range. If this is a function-like
771 // macro, we'd also like to highlight the arguments.
772 if (B == E && Info.getRange(i).getEnd().isMacroID())
773 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
774
775 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000776 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000777
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000778 // If the start or end of the range is in another file, just discard
779 // it.
780 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
781 continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000782
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000783 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner0a76aae2010-06-18 22:45:06 +0000784 unsigned TokSize = 0;
785 if (Info.getRange(i).isTokenRange())
786 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000787
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000788 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
789 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
790 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
791 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
792 PrintedRange = true;
793 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000794
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000795 if (PrintedRange)
796 OS << ':';
797 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000798 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000799 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000800 OS.resetColor();
801 }
802 }
803
Daniel Dunbareace8742009-11-04 06:24:30 +0000804 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000805 // Print diagnostic category in bold and color
806 switch (Level) {
807 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
808 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
809 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
810 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
811 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000812 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000813 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000814
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000816 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000817 case Diagnostic::Note: OS << "note: "; break;
818 case Diagnostic::Warning: OS << "warning: "; break;
819 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000820 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000821 }
Torok Edwin603fca72009-06-04 07:18:23 +0000822
Daniel Dunbareace8742009-11-04 06:24:30 +0000823 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000824 OS.resetColor();
825
Chris Lattnerf4c83962008-11-19 06:51:40 +0000826 llvm::SmallString<100> OutStr;
827 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000828
Chris Lattnerc9b88902010-05-04 21:13:21 +0000829 std::string OptionName;
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000830 if (DiagOpts->ShowOptionNames) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000831 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
Chris Lattnerc9b88902010-05-04 21:13:21 +0000832 OptionName = "-W";
833 OptionName += Opt;
Chris Lattnerd342bf72010-05-24 18:37:03 +0000834 } else if (Info.getID() == diag::fatal_too_many_errors) {
835 OptionName = "-ferror-limit=";
Chris Lattner04e44272010-04-12 21:53:11 +0000836 } else {
837 // If the diagnostic is an extension diagnostic and not enabled by default
838 // then it must have been turned on with -pedantic.
839 bool EnabledByDefault;
840 if (Diagnostic::isBuiltinExtensionDiag(Info.getID(), EnabledByDefault) &&
841 !EnabledByDefault)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000842 OptionName = "-pedantic";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000843 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000844 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000845
846 // If the user wants to see category information, include it too.
847 unsigned DiagCategory = 0;
Chris Lattner6fbe8392010-05-04 21:55:25 +0000848 if (DiagOpts->ShowCategories)
Chris Lattnerc9b88902010-05-04 21:13:21 +0000849 DiagCategory = Diagnostic::getCategoryNumberForDiag(Info.getID());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000850
Chris Lattnerc9b88902010-05-04 21:13:21 +0000851 // If there is any categorization information, include it.
852 if (!OptionName.empty() || DiagCategory != 0) {
853 bool NeedsComma = false;
854 OutStr += " [";
855
856 if (!OptionName.empty()) {
857 OutStr += OptionName;
858 NeedsComma = true;
859 }
860
861 if (DiagCategory) {
862 if (NeedsComma) OutStr += ',';
Chris Lattner6fbe8392010-05-04 21:55:25 +0000863 if (DiagOpts->ShowCategories == 1)
864 OutStr += llvm::utostr(DiagCategory);
865 else {
866 assert(DiagOpts->ShowCategories == 2 && "Invalid ShowCategories value");
867 OutStr += Diagnostic::getCategoryNameFromID(DiagCategory);
868 }
Chris Lattnerc9b88902010-05-04 21:13:21 +0000869 }
870
871 OutStr += "]";
872 }
873
874
Daniel Dunbareace8742009-11-04 06:24:30 +0000875 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000876 // Print warnings, errors and fatal errors in bold, no color
877 switch (Level) {
878 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
879 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
880 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
881 default: break; //don't bold notes
882 }
883 }
884
Daniel Dunbareace8742009-11-04 06:24:30 +0000885 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000886 // We will be word-wrapping the error message, so compute the
887 // column number where we currently are (after printing the
888 // location information).
889 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +0000890 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000891 } else {
892 OS.write(OutStr.begin(), OutStr.size());
893 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000894 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000895 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000896 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000897
Douglas Gregordf667e72009-03-10 20:44:00 +0000898 // If caret diagnostics are enabled and we have location, we want to
899 // emit the caret. However, we only do this if the location moved
900 // from the last diagnostic, if the last diagnostic was a note that
901 // was part of a different warning or error diagnostic, or if the
902 // diagnostic has ranges. We don't want to emit the same caret
903 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +0000904 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000905 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000906 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +0000907 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000908 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000909 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000910 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000911
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000912 // Get the ranges into a local array we can hack on.
Chris Lattner0a76aae2010-06-18 22:45:06 +0000913 CharSourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000914 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000915 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000916 for (unsigned i = 0; i != NumRanges; ++i)
917 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000918
Douglas Gregor849b2432010-03-31 17:46:05 +0000919 unsigned NumHints = Info.getNumFixItHints();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000920 for (unsigned i = 0; i != NumHints; ++i) {
921 const FixItHint &Hint = Info.getFixItHint(i);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000922 if (Hint.RemoveRange.isValid()) {
923 assert(NumRanges < 20 && "Out of space");
924 Ranges[NumRanges++] = Hint.RemoveRange;
925 }
926 }
927
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000928 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
929 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
930 // Compute the length of the macro-instantiation backtrace, so that we
931 // can establish which steps in the macro backtrace we'll skip.
932 SourceLocation Loc = LastLoc;
933 unsigned Depth = 0;
934 do {
935 ++Depth;
936 Loc = LastLoc.getManager().getImmediateInstantiationRange(Loc).first;
937 } while (!Loc.isFileID());
938
939 if (Depth > DiagOpts->MacroBacktraceLimit) {
940 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
941 DiagOpts->MacroBacktraceLimit % 2;
942 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
943 }
944 }
945
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000946 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000947 Info.getFixItHints(),
948 Info.getNumFixItHints(),
Douglas Gregor6c1cb992010-05-04 17:13:42 +0000949 DiagOpts->MessageLength,
950 0, MacroInstSkipStart, MacroInstSkipEnd);
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000952
Chris Lattnera03a5b52008-11-19 06:56:25 +0000953 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000954}