blob: f2b16a4b386966957086d4f4af22abe2a776e43b [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"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000021#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Torok Edwin603fca72009-06-04 07:18:23 +000024static const enum llvm::raw_ostream::Colors noteColor =
25 llvm::raw_ostream::BLACK;
26static const enum llvm::raw_ostream::Colors fixitColor =
27 llvm::raw_ostream::GREEN;
28static const enum llvm::raw_ostream::Colors caretColor =
29 llvm::raw_ostream::GREEN;
30static const enum llvm::raw_ostream::Colors warningColor =
31 llvm::raw_ostream::MAGENTA;
32static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
33static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000034// Used for changing only the bold attribute.
Torok Edwin603fca72009-06-04 07:18:23 +000035static const enum llvm::raw_ostream::Colors savedColor =
36 llvm::raw_ostream::SAVEDCOLOR;
37
Douglas Gregorfffd93f2009-05-01 21:53:04 +000038/// \brief Number of spaces to indent when word-wrapping.
39const unsigned WordWrapIndentation = 6;
40
Daniel Dunbareace8742009-11-04 06:24:30 +000041TextDiagnosticPrinter::TextDiagnosticPrinter(llvm::raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000042 const DiagnosticOptions &diags,
43 bool _OwnsOutputStream)
Daniel Dunbareace8742009-11-04 06:24:30 +000044 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbaraea36412009-11-11 09:38:24 +000045 LastCaretDiagnosticWasNote(0),
46 OwnsOutputStream(_OwnsOutputStream) {
47}
48
49TextDiagnosticPrinter::~TextDiagnosticPrinter() {
50 if (OwnsOutputStream)
51 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000052}
53
Reid Spencer5f016e22007-07-11 17:01:13 +000054void TextDiagnosticPrinter::
Chris Lattnerb9c3f962009-01-27 07:57:44 +000055PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
56 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000057
Chris Lattnerb9c3f962009-01-27 07:57:44 +000058 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner9dc1f532007-07-20 16:37:10 +000059
Reid Spencer5f016e22007-07-11 17:01:13 +000060 // Print out the other include frames first.
Chris Lattnerb9c3f962009-01-27 07:57:44 +000061 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000062
Daniel Dunbareace8742009-11-04 06:24:30 +000063 if (DiagOpts->ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000064 OS << "In file included from " << PLoc.getFilename()
65 << ':' << PLoc.getLine() << ":\n";
66 else
67 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000068}
69
70/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
71/// any characters in LineNo that intersect the SourceRange.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000072void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000073 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000074 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000075 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000076 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000077 assert(CaretLine.size() == SourceLine.size() &&
78 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000079 if (!R.isValid()) return;
80
Chris Lattnerb9c3f962009-01-27 07:57:44 +000081 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
82 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000083
Chris Lattner34837a52009-02-17 05:19:10 +000084 // If the End location and the start location are the same and are a macro
85 // location, then the range was something that came from a macro expansion
86 // or _Pragma. If this is an object-like macro, the best we can do is to
87 // highlight the range. If this is a function-like macro, we'd also like to
88 // highlight the arguments.
89 if (Begin == End && R.getEnd().isMacroID())
90 End = SM.getInstantiationRange(R.getEnd()).second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000091
Chris Lattner30fc9332009-02-04 01:06:56 +000092 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000093 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000094 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000095
Chris Lattner30fc9332009-02-04 01:06:56 +000096 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000097 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000098 return; // No intersection.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +000099
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 // Compute the column number of the start.
101 unsigned StartColNo = 0;
102 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000103 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +0000104 if (StartColNo) --StartColNo; // Zero base the col #.
105 }
106
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +0000108 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000110 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 if (EndColNo) {
112 --EndColNo; // Zero base the col #.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000113
Reid Spencer5f016e22007-07-11 17:01:13 +0000114 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000115 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000117 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000118 }
119 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000120
Chris Lattner41e79e22010-02-12 18:52:52 +0000121 assert(StartColNo <= EndColNo && "Invalid range!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000122
Chris Lattner41e79e22010-02-12 18:52:52 +0000123 // Pick the first non-whitespace column.
124 while (StartColNo < SourceLine.size() &&
125 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
126 ++StartColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000127
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 // Pick the last non-whitespace column.
Chris Lattner41e79e22010-02-12 18:52:52 +0000129 if (EndColNo > SourceLine.size())
Nuno Lopesdb825682008-08-05 19:40:20 +0000130 EndColNo = SourceLine.size();
Chris Lattner41e79e22010-02-12 18:52:52 +0000131 while (EndColNo-1 &&
132 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
133 --EndColNo;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000134
Chris Lattner41e79e22010-02-12 18:52:52 +0000135 // If the start/end passed each other, then we are trying to highlight a range
136 // that just exists in whitespace, which must be some sort of other bug.
137 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000138
Reid Spencer5f016e22007-07-11 17:01:13 +0000139 // Fill the range with ~'s.
Nuno Lopesdb825682008-08-05 19:40:20 +0000140 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000141 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000142}
143
Douglas Gregor47f71772009-05-01 23:32:58 +0000144/// \brief When the source code line we want to print is too long for
145/// the terminal, select the "interesting" region.
146static void SelectInterestingSourceRegion(std::string &SourceLine,
147 std::string &CaretLine,
148 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000149 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000150 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000151 unsigned MaxSize = std::max(SourceLine.size(),
152 std::max(CaretLine.size(),
153 FixItInsertionLine.size()));
154 if (MaxSize > SourceLine.size())
155 SourceLine.resize(MaxSize, ' ');
156 if (MaxSize > CaretLine.size())
157 CaretLine.resize(MaxSize, ' ');
158 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
159 FixItInsertionLine.resize(MaxSize, ' ');
160
Douglas Gregor47f71772009-05-01 23:32:58 +0000161 // Find the slice that we need to display the full caret line
162 // correctly.
163 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
164 for (; CaretStart != CaretEnd; ++CaretStart)
165 if (!isspace(CaretLine[CaretStart]))
166 break;
167
168 for (; CaretEnd != CaretStart; --CaretEnd)
169 if (!isspace(CaretLine[CaretEnd - 1]))
170 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000171
172 // Make sure we don't chop the string shorter than the caret token
173 // itself.
174 if (CaretEnd < EndOfCaretToken)
175 CaretEnd = EndOfCaretToken;
176
Douglas Gregor844da342009-05-03 04:33:32 +0000177 // If we have a fix-it line, make sure the slice includes all of the
178 // fix-it information.
179 if (!FixItInsertionLine.empty()) {
180 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
181 for (; FixItStart != FixItEnd; ++FixItStart)
182 if (!isspace(FixItInsertionLine[FixItStart]))
183 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000184
Douglas Gregor844da342009-05-03 04:33:32 +0000185 for (; FixItEnd != FixItStart; --FixItEnd)
186 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
187 break;
188
189 if (FixItStart < CaretStart)
190 CaretStart = FixItStart;
191 if (FixItEnd > CaretEnd)
192 CaretEnd = FixItEnd;
193 }
194
Douglas Gregor47f71772009-05-01 23:32:58 +0000195 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
196 // parts of the caret line. While this slice is smaller than the
197 // number of columns we have, try to grow the slice to encompass
198 // more context.
199
200 // If the end of the interesting region comes before we run out of
201 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000202 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000203 CaretStart = 0;
204
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000205 unsigned TargetColumns = Columns;
206 if (TargetColumns > 8)
207 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000208 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000209 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000210 bool ExpandedRegion = false;
211 // Move the start of the interesting region left until we've
212 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000213 if (CaretStart == 1)
214 CaretStart = 0;
215 else if (CaretStart > 1) {
216 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000217
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000218 // Skip over any whitespace we see here; we're looking for
219 // another bit of interesting text.
220 while (NewStart && isspace(SourceLine[NewStart]))
221 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000222
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000223 // Skip over this bit of "interesting" text.
224 while (NewStart && !isspace(SourceLine[NewStart]))
225 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000226
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000227 // Move up to the non-whitespace character we just saw.
228 if (NewStart)
229 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000230
231 // If we're still within our limit, update the starting
232 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000233 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000234 CaretStart = NewStart;
235 ExpandedRegion = true;
236 }
237 }
238
239 // Move the end of the interesting region right until we've
240 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000241 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000242 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000243 unsigned NewEnd = CaretEnd;
244
245 // Skip over any whitespace we see here; we're looking for
246 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000247 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000248 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000249
Douglas Gregor47f71772009-05-01 23:32:58 +0000250 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000251 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000252 ++NewEnd;
253
254 if (NewEnd - CaretStart <= TargetColumns) {
255 CaretEnd = NewEnd;
256 ExpandedRegion = true;
257 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000258 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000259
260 if (!ExpandedRegion)
261 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000262 }
263
264 // [CaretStart, CaretEnd) is the slice we want. Update the various
265 // output lines to show only this slice, with two-space padding
266 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000267 if (CaretEnd < SourceLine.size())
268 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000269 if (CaretEnd < CaretLine.size())
270 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000271 if (FixItInsertionLine.size() > CaretEnd)
272 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000273
Douglas Gregor47f71772009-05-01 23:32:58 +0000274 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000275 SourceLine.replace(0, CaretStart, " ...");
276 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000277 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000278 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000279 }
280}
281
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000282void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner676f0242009-02-20 00:25:28 +0000283 SourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000284 unsigned NumRanges,
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000285 SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000286 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000287 unsigned NumHints,
Douglas Gregor47f71772009-05-01 23:32:58 +0000288 unsigned Columns) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000289 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000290 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000291
292 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000293 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000294 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000295 if (!Loc.isFileID()) {
Chris Lattner609b3ab2009-02-18 18:50:45 +0000296 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000297 // FIXME: Map ranges?
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000298 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
Chris Lattner676f0242009-02-20 00:25:28 +0000299
Chris Lattner2e77aa12009-12-04 07:06:35 +0000300 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000301 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000302
Chris Lattner676f0242009-02-20 00:25:28 +0000303 // Map the ranges.
304 for (unsigned i = 0; i != NumRanges; ++i) {
305 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000306 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
307 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000308 Ranges[i] = SourceRange(S, E);
309 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000310
Chris Lattner2e77aa12009-12-04 07:06:35 +0000311 // Get the pretty name, according to #line directives etc.
312 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000313
Chris Lattner2e77aa12009-12-04 07:06:35 +0000314 // If this diagnostic is not in the main file, print out the "included from"
315 // lines.
316 if (LastWarningLoc != PLoc.getIncludeLoc()) {
317 LastWarningLoc = PLoc.getIncludeLoc();
318 PrintIncludeStack(LastWarningLoc, SM);
319 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000320
Daniel Dunbareace8742009-11-04 06:24:30 +0000321 if (DiagOpts->ShowLocation) {
Chris Lattner5ce24c82009-04-21 03:57:54 +0000322 // Emit the file/line/column that this expansion came from.
Chris Lattner2e77aa12009-12-04 07:06:35 +0000323 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
Daniel Dunbareace8742009-11-04 06:24:30 +0000324 if (DiagOpts->ShowColumn)
Chris Lattner2e77aa12009-12-04 07:06:35 +0000325 OS << PLoc.getColumn() << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000326 OS << ' ';
327 }
328 OS << "note: instantiated from:\n";
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000329
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000330 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
Chris Lattner037fb7f2009-05-05 22:03:18 +0000331 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000332 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000333
Chris Lattnerb88af812009-02-17 07:51:53 +0000334 // Decompose the location into a FID/Offset pair.
335 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
336 FileID FID = LocInfo.first;
337 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000338
Chris Lattnerb88af812009-02-17 07:51:53 +0000339 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000340 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000341 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000342 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000343 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000344
Chris Lattnerb88af812009-02-17 07:51:53 +0000345 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000346 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000347 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
348
Chris Lattner94f55782009-02-17 07:38:37 +0000349 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000350 const char *TokPtr = BufStart+FileOffset;
351 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000352
353
Chris Lattner94f55782009-02-17 07:38:37 +0000354 // Compute the line end. Scan forward from the error position to the end of
355 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000356 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000357 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000358 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000359
Daniel Dunbar06d10722009-10-19 09:11:21 +0000360 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
361 // the source line length as currently being computed. See
362 // test/Misc/message-length.c.
363 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
364
Chris Lattner94f55782009-02-17 07:38:37 +0000365 // Copy the line of code into an std::string for ease of manipulation.
366 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000367
Chris Lattner94f55782009-02-17 07:38:37 +0000368 // Create a line for the caret that is filled with spaces that is the same
369 // length as the line of source code.
370 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000371
Chris Lattner94f55782009-02-17 07:38:37 +0000372 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000373 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000374 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000375
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000376 for (unsigned i = 0, e = NumRanges; i != e; ++i)
377 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000378 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000379
Chris Lattner94f55782009-02-17 07:38:37 +0000380 // Next, insert the caret itself.
381 if (ColNo-1 < CaretLine.size())
382 CaretLine[ColNo-1] = '^';
383 else
384 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000385
Chris Lattner94f55782009-02-17 07:38:37 +0000386 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000387 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000388 for (unsigned i = 0; i != SourceLine.size(); ++i) {
389 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000390
Chris Lattner94f55782009-02-17 07:38:37 +0000391 // Replace this tab with at least one space.
392 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000393
Chris Lattner94f55782009-02-17 07:38:37 +0000394 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000395 unsigned TabStop = DiagOpts->TabStop;
396 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
397 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000398 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
399 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000400
Chris Lattner94f55782009-02-17 07:38:37 +0000401 // Insert spaces into the SourceLine.
402 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000403
Chris Lattner94f55782009-02-17 07:38:37 +0000404 // Insert spaces or ~'s into CaretLine.
405 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
406 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000407
Chris Lattner770dbf02009-04-28 22:33:16 +0000408 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
409 // produce easily machine parsable output. Add a space before the source line
410 // and the caret to make it trivial to tell the main diagnostic line from what
411 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000412 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000413 SourceLine = ' ' + SourceLine;
414 CaretLine = ' ' + CaretLine;
415 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000416
Douglas Gregor47f71772009-05-01 23:32:58 +0000417 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000418 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000419 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000420 Hint != LastHint; ++Hint) {
421 if (Hint->InsertionLoc.isValid()) {
422 // We have an insertion hint. Determine whether the inserted
423 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000424 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000425 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000426 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
427 SM.getLineNumber(FID, FileOffset)) {
428 // Insert the new code into the line just below the code
429 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000430 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000431 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000432 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000433 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000434 if (LastColumnModified > FixItInsertionLine.size())
435 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000436 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000437 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000438 } else {
439 FixItInsertionLine.clear();
440 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000441 }
442 }
443 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000444 // Now that we have the entire fixit line, expand the tabs in it.
445 // Since we don't want to insert spaces in the middle of a word,
446 // find each word and the column it should line up with and insert
447 // spaces until they match.
448 if (!FixItInsertionLine.empty()) {
449 unsigned FixItPos = 0;
450 unsigned LinePos = 0;
451 unsigned TabExpandedCol = 0;
452 unsigned LineLength = LineEnd - LineStart;
453
454 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
455 // Find the next word in the FixIt line.
456 while (FixItPos < FixItInsertionLine.size() &&
457 FixItInsertionLine[FixItPos] == ' ')
458 ++FixItPos;
459 unsigned CharDistance = FixItPos - TabExpandedCol;
460
461 // Walk forward in the source line, keeping track of
462 // the tab-expanded column.
463 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
464 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
465 ++TabExpandedCol;
466 else
467 TabExpandedCol =
468 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
469
470 // Adjust the fixit line to match this column.
471 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
472 FixItPos = TabExpandedCol;
473
474 // Walk to the end of the word.
475 while (FixItPos < FixItInsertionLine.size() &&
476 FixItInsertionLine[FixItPos] != ' ')
477 ++FixItPos;
478 }
479 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000480 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000481
Douglas Gregor47f71772009-05-01 23:32:58 +0000482 // If the source line is too long for our terminal, select only the
483 // "interesting" source region within that line.
484 if (Columns && SourceLine.size() > Columns)
485 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000486 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000487
Douglas Gregor47f71772009-05-01 23:32:58 +0000488 // Finally, remove any blank spaces from the end of CaretLine.
489 while (CaretLine[CaretLine.size()-1] == ' ')
490 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000491
Douglas Gregor47f71772009-05-01 23:32:58 +0000492 // Emit what we have computed.
493 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000494
Daniel Dunbareace8742009-11-04 06:24:30 +0000495 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000496 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000497 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000498 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000499 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000500
501 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000502 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000503 // Print fixit line in color
504 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000505 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000506 OS << ' ';
507 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000508 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000509 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000510 }
Chris Lattner94f55782009-02-17 07:38:37 +0000511}
512
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000513/// \brief Skip over whitespace in the string, starting at the given
514/// index.
515///
516/// \returns The index of the first non-whitespace character that is
517/// greater than or equal to Idx or, if no such character exists,
518/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000519static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000521 unsigned Length) {
522 while (Idx < Length && isspace(Str[Idx]))
523 ++Idx;
524 return Idx;
525}
526
527/// \brief If the given character is the start of some kind of
528/// balanced punctuation (e.g., quotes or parentheses), return the
529/// character that will terminate the punctuation.
530///
531/// \returns The ending punctuation character, if any, or the NULL
532/// character if the input character does not start any punctuation.
533static inline char findMatchingPunctuation(char c) {
534 switch (c) {
535 case '\'': return '\'';
536 case '`': return '\'';
537 case '"': return '"';
538 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000539 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000540 case '{': return '}';
541 default: break;
542 }
543
544 return 0;
545}
546
547/// \brief Find the end of the word starting at the given offset
548/// within a string.
549///
550/// \returns the index pointing one character past the end of the
551/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000552static unsigned findEndOfWord(unsigned Start,
553 const llvm::SmallVectorImpl<char> &Str,
554 unsigned Length, unsigned Column,
555 unsigned Columns) {
556 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000557 unsigned End = Start + 1;
558
Daniel Dunbareae18f82009-12-06 09:56:18 +0000559 // If we are already at the end of the string, take that as the word.
560 if (End == Str.size())
561 return End;
562
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000563 // Determine if the start of the string is actually opening
564 // punctuation, e.g., a quote or parentheses.
565 char EndPunct = findMatchingPunctuation(Str[Start]);
566 if (!EndPunct) {
567 // This is a normal word. Just find the first space character.
568 while (End < Length && !isspace(Str[End]))
569 ++End;
570 return End;
571 }
572
573 // We have the start of a balanced punctuation sequence (quotes,
574 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000575 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000576 PunctuationEndStack.push_back(EndPunct);
577 while (End < Length && !PunctuationEndStack.empty()) {
578 if (Str[End] == PunctuationEndStack.back())
579 PunctuationEndStack.pop_back();
580 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
581 PunctuationEndStack.push_back(SubEndPunct);
582
583 ++End;
584 }
585
586 // Find the first space character after the punctuation ended.
587 while (End < Length && !isspace(Str[End]))
588 ++End;
589
590 unsigned PunctWordLength = End - Start;
591 if (// If the word fits on this line
592 Column + PunctWordLength <= Columns ||
593 // ... or the word is "short enough" to take up the next line
594 // without too much ugly white space
595 PunctWordLength < Columns/3)
596 return End; // Take the whole thing as a single "word".
597
598 // The whole quoted/parenthesized string is too long to print as a
599 // single "word". Instead, find the "word" that starts just after
600 // the punctuation and use that end-point instead. This will recurse
601 // until it finds something small enough to consider a word.
602 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
603}
604
605/// \brief Print the given string to a stream, word-wrapping it to
606/// some number of columns in the process.
607///
608/// \brief OS the stream to which the word-wrapping string will be
609/// emitted.
610///
611/// \brief Str the string to word-wrap and output.
612///
613/// \brief Columns the number of columns to word-wrap to.
614///
615/// \brief Column the column number at which the first character of \p
616/// Str will be printed. This will be non-zero when part of the first
617/// line has already been printed.
618///
619/// \brief Indentation the number of spaces to indent any lines beyond
620/// the first line.
621///
622/// \returns true if word-wrapping was required, or false if the
623/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000624static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000625 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000626 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000627 unsigned Column = 0,
628 unsigned Indentation = WordWrapIndentation) {
629 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000630
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000631 // If there is a newline in this message somewhere, find that
632 // newline and split the message into the part before the newline
633 // (which will be word-wrapped) and the part from the newline one
634 // (which will be emitted unchanged).
635 for (unsigned I = 0; I != Length; ++I)
636 if (Str[I] == '\n') {
637 Length = I;
638 break;
639 }
640
641 // The string used to indent each line.
642 llvm::SmallString<16> IndentStr;
643 IndentStr.assign(Indentation, ' ');
644 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000645 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000646 WordStart = WordEnd) {
647 // Find the beginning of the next word.
648 WordStart = skipWhitespace(WordStart, Str, Length);
649 if (WordStart == Length)
650 break;
651
652 // Find the end of this word.
653 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000654
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000655 // Does this word fit on the current line?
656 unsigned WordLength = WordEnd - WordStart;
657 if (Column + WordLength < Columns) {
658 // This word fits on the current line; print it there.
659 if (WordStart) {
660 OS << ' ';
661 Column += 1;
662 }
663 OS.write(&Str[WordStart], WordLength);
664 Column += WordLength;
665 continue;
666 }
667
668 // This word does not fit on the current line, so wrap to the next
669 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000670 OS << '\n';
671 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000672 OS.write(&Str[WordStart], WordLength);
673 Column = Indentation + WordLength;
674 Wrapped = true;
675 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000676
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000677 if (Length == Str.size())
678 return Wrapped; // We're done.
679
680 // There is a newline in the message, followed by something that
681 // will not be word-wrapped. Print that.
682 OS.write(&Str[Length], Str.size() - Length);
683 return true;
684}
Chris Lattner94f55782009-02-17 07:38:37 +0000685
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000686void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000687 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000688 // Keeps track of the the starting position of the location
689 // information (e.g., "foo.c:10:4:") that precedes the error
690 // message. We use this information to determine how long the
691 // file+line+column number prefix is.
692 uint64_t StartOfLocationInfo = OS.tell();
693
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000694 if (!Prefix.empty())
695 OS << Prefix << ": ";
696
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000697 // If the location is specified, print out a file/line/col and include trace
698 // if enabled.
699 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000700 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000701 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
702 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000703
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 // First, if this diagnostic is not in the main file, print out the
705 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000706 if (LastWarningLoc != PLoc.getIncludeLoc()) {
707 LastWarningLoc = PLoc.getIncludeLoc();
708 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000709 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000711
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000712 // Compute the column number.
Daniel Dunbareace8742009-11-04 06:24:30 +0000713 if (DiagOpts->ShowLocation) {
714 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000715 OS.changeColor(savedColor, true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000716
Steve Naroffe0c4d892009-12-05 02:14:08 +0000717 // Emit a Visual Studio compatible line number syntax.
Steve Naroff0304c6c2009-12-05 12:23:07 +0000718 if (LangOpts && LangOpts->Microsoft) {
Steve Naroffe0c4d892009-12-05 02:14:08 +0000719 OS << PLoc.getFilename() << '(' << LineNo << ')';
720 OS << " : ";
721 } else {
722 OS << PLoc.getFilename() << ':' << LineNo << ':';
723 if (DiagOpts->ShowColumn)
724 if (unsigned ColNo = PLoc.getColumn())
725 OS << ColNo << ':';
726 }
Daniel Dunbareace8742009-11-04 06:24:30 +0000727 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000728 FileID CaretFileID =
729 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
730 bool PrintedRange = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000731
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000732 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000733 // Ignore invalid ranges.
734 if (!Info.getRange(i).isValid()) continue;
735
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000736 SourceLocation B = Info.getRange(i).getBegin();
737 SourceLocation E = Info.getRange(i).getEnd();
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000738 B = SM.getInstantiationLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000739 E = SM.getInstantiationLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000740
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000741 // If the End location and the start location are the same and are a
742 // macro location, then the range was something that came from a macro
743 // expansion or _Pragma. If this is an object-like macro, the best we
744 // can do is to highlight the range. If this is a function-like
745 // macro, we'd also like to highlight the arguments.
746 if (B == E && Info.getRange(i).getEnd().isMacroID())
747 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
748
749 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000750 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000751
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000752 // If the start or end of the range is in another file, just discard
753 // it.
754 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
755 continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000756
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000757 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000758 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000759
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000760 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
761 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
762 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
763 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
764 PrintedRange = true;
765 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000766
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000767 if (PrintedRange)
768 OS << ':';
769 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000770 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000771 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000772 OS.resetColor();
773 }
774 }
775
Daniel Dunbareace8742009-11-04 06:24:30 +0000776 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000777 // Print diagnostic category in bold and color
778 switch (Level) {
779 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
780 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
781 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
782 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
783 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000784 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000785 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000786
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000788 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000789 case Diagnostic::Note: OS << "note: "; break;
790 case Diagnostic::Warning: OS << "warning: "; break;
791 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000792 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 }
Torok Edwin603fca72009-06-04 07:18:23 +0000794
Daniel Dunbareace8742009-11-04 06:24:30 +0000795 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000796 OS.resetColor();
797
Chris Lattnerf4c83962008-11-19 06:51:40 +0000798 llvm::SmallString<100> OutStr;
799 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000800
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000801 if (DiagOpts->ShowOptionNames) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000802 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
803 OutStr += " [-W";
804 OutStr += Opt;
805 OutStr += ']';
Chris Lattner04e44272010-04-12 21:53:11 +0000806 } else {
807 // If the diagnostic is an extension diagnostic and not enabled by default
808 // then it must have been turned on with -pedantic.
809 bool EnabledByDefault;
810 if (Diagnostic::isBuiltinExtensionDiag(Info.getID(), EnabledByDefault) &&
811 !EnabledByDefault)
812 OutStr += " [-pedantic]";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000813 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000814 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000815
Daniel Dunbareace8742009-11-04 06:24:30 +0000816 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000817 // Print warnings, errors and fatal errors in bold, no color
818 switch (Level) {
819 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
820 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
821 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
822 default: break; //don't bold notes
823 }
824 }
825
Daniel Dunbareace8742009-11-04 06:24:30 +0000826 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000827 // We will be word-wrapping the error message, so compute the
828 // column number where we currently are (after printing the
829 // location information).
830 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +0000831 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000832 } else {
833 OS.write(OutStr.begin(), OutStr.size());
834 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000835 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000836 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000837 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000838
Douglas Gregordf667e72009-03-10 20:44:00 +0000839 // If caret diagnostics are enabled and we have location, we want to
840 // emit the caret. However, we only do this if the location moved
841 // from the last diagnostic, if the last diagnostic was a note that
842 // was part of a different warning or error diagnostic, or if the
843 // diagnostic has ranges. We don't want to emit the same caret
844 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +0000845 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000846 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000847 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +0000848 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000849 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000850 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000851 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000852
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000853 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000854 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000855 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000856 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000857 for (unsigned i = 0; i != NumRanges; ++i)
858 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000859
Douglas Gregor849b2432010-03-31 17:46:05 +0000860 unsigned NumHints = Info.getNumFixItHints();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000861 for (unsigned idx = 0; idx < NumHints; ++idx) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000862 const FixItHint &Hint = Info.getFixItHint(idx);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000863 if (Hint.RemoveRange.isValid()) {
864 assert(NumRanges < 20 && "Out of space");
865 Ranges[NumRanges++] = Hint.RemoveRange;
866 }
867 }
868
869 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000870 Info.getFixItHints(),
871 Info.getNumFixItHints(),
Daniel Dunbareace8742009-11-04 06:24:30 +0000872 DiagOpts->MessageLength);
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000874
Chris Lattnera03a5b52008-11-19 06:56:25 +0000875 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000876}