blob: 4e91f8d4c221f0e8e238f837c271c3d3d1e9d3e0 [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) {
151 if (CaretLine.size() > SourceLine.size())
152 SourceLine.resize(CaretLine.size(), ' ');
153
154 // Find the slice that we need to display the full caret line
155 // correctly.
156 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
157 for (; CaretStart != CaretEnd; ++CaretStart)
158 if (!isspace(CaretLine[CaretStart]))
159 break;
160
161 for (; CaretEnd != CaretStart; --CaretEnd)
162 if (!isspace(CaretLine[CaretEnd - 1]))
163 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000164
165 // Make sure we don't chop the string shorter than the caret token
166 // itself.
167 if (CaretEnd < EndOfCaretToken)
168 CaretEnd = EndOfCaretToken;
169
Douglas Gregor844da342009-05-03 04:33:32 +0000170 // If we have a fix-it line, make sure the slice includes all of the
171 // fix-it information.
172 if (!FixItInsertionLine.empty()) {
173 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
174 for (; FixItStart != FixItEnd; ++FixItStart)
175 if (!isspace(FixItInsertionLine[FixItStart]))
176 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000177
Douglas Gregor844da342009-05-03 04:33:32 +0000178 for (; FixItEnd != FixItStart; --FixItEnd)
179 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
180 break;
181
182 if (FixItStart < CaretStart)
183 CaretStart = FixItStart;
184 if (FixItEnd > CaretEnd)
185 CaretEnd = FixItEnd;
186 }
187
Douglas Gregor47f71772009-05-01 23:32:58 +0000188 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
189 // parts of the caret line. While this slice is smaller than the
190 // number of columns we have, try to grow the slice to encompass
191 // more context.
192
193 // If the end of the interesting region comes before we run out of
194 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000195 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000196 CaretStart = 0;
197
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000198 unsigned TargetColumns = Columns;
199 if (TargetColumns > 8)
200 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000201 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000202 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000203 bool ExpandedRegion = false;
204 // Move the start of the interesting region left until we've
205 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000206 if (CaretStart == 1)
207 CaretStart = 0;
208 else if (CaretStart > 1) {
209 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000210
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000211 // Skip over any whitespace we see here; we're looking for
212 // another bit of interesting text.
213 while (NewStart && isspace(SourceLine[NewStart]))
214 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000215
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000216 // Skip over this bit of "interesting" text.
217 while (NewStart && !isspace(SourceLine[NewStart]))
218 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000219
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000220 // Move up to the non-whitespace character we just saw.
221 if (NewStart)
222 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000223
224 // If we're still within our limit, update the starting
225 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000226 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000227 CaretStart = NewStart;
228 ExpandedRegion = true;
229 }
230 }
231
232 // Move the end of the interesting region right until we've
233 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000234 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000235 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000236 unsigned NewEnd = CaretEnd;
237
238 // Skip over any whitespace we see here; we're looking for
239 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000240 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000241 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000242
Douglas Gregor47f71772009-05-01 23:32:58 +0000243 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000244 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000245 ++NewEnd;
246
247 if (NewEnd - CaretStart <= TargetColumns) {
248 CaretEnd = NewEnd;
249 ExpandedRegion = true;
250 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000251 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000252
253 if (!ExpandedRegion)
254 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000255 }
256
257 // [CaretStart, CaretEnd) is the slice we want. Update the various
258 // output lines to show only this slice, with two-space padding
259 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000260 if (CaretEnd < SourceLine.size())
261 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000262 if (CaretEnd < CaretLine.size())
263 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000264 if (FixItInsertionLine.size() > CaretEnd)
265 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000266
Douglas Gregor47f71772009-05-01 23:32:58 +0000267 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000268 SourceLine.replace(0, CaretStart, " ...");
269 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000270 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000271 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000272 }
273}
274
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000275void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner676f0242009-02-20 00:25:28 +0000276 SourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000277 unsigned NumRanges,
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000278 SourceManager &SM,
Douglas Gregor849b2432010-03-31 17:46:05 +0000279 const FixItHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000280 unsigned NumHints,
Douglas Gregor47f71772009-05-01 23:32:58 +0000281 unsigned Columns) {
Daniel Dunbarefcbe942009-11-05 02:42:12 +0000282 assert(LangOpts && "Unexpected diagnostic outside source file processing");
Chris Lattner55dcef02009-02-17 08:44:50 +0000283 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000284
285 // If this is a macro ID, first emit information about where this was
Chris Lattner2e77aa12009-12-04 07:06:35 +0000286 // instantiated (recursively) then emit information about where the token was
Chris Lattner037fb7f2009-05-05 22:03:18 +0000287 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000288 if (!Loc.isFileID()) {
Chris Lattner609b3ab2009-02-18 18:50:45 +0000289 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000290 // FIXME: Map ranges?
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000291 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
Chris Lattner676f0242009-02-20 00:25:28 +0000292
Chris Lattner2e77aa12009-12-04 07:06:35 +0000293 // Map the location.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000294 Loc = SM.getImmediateSpellingLoc(Loc);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000295
Chris Lattner676f0242009-02-20 00:25:28 +0000296 // Map the ranges.
297 for (unsigned i = 0; i != NumRanges; ++i) {
298 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000299 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
300 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000301 Ranges[i] = SourceRange(S, E);
302 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000303
Chris Lattner2e77aa12009-12-04 07:06:35 +0000304 // Get the pretty name, according to #line directives etc.
305 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000306
Chris Lattner2e77aa12009-12-04 07:06:35 +0000307 // If this diagnostic is not in the main file, print out the "included from"
308 // lines.
309 if (LastWarningLoc != PLoc.getIncludeLoc()) {
310 LastWarningLoc = PLoc.getIncludeLoc();
311 PrintIncludeStack(LastWarningLoc, SM);
312 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000313
Daniel Dunbareace8742009-11-04 06:24:30 +0000314 if (DiagOpts->ShowLocation) {
Chris Lattner5ce24c82009-04-21 03:57:54 +0000315 // Emit the file/line/column that this expansion came from.
Chris Lattner2e77aa12009-12-04 07:06:35 +0000316 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
Daniel Dunbareace8742009-11-04 06:24:30 +0000317 if (DiagOpts->ShowColumn)
Chris Lattner2e77aa12009-12-04 07:06:35 +0000318 OS << PLoc.getColumn() << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000319 OS << ' ';
320 }
321 OS << "note: instantiated from:\n";
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000322
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000323 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
Chris Lattner037fb7f2009-05-05 22:03:18 +0000324 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000325 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000326
Chris Lattnerb88af812009-02-17 07:51:53 +0000327 // Decompose the location into a FID/Offset pair.
328 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
329 FileID FID = LocInfo.first;
330 unsigned FileOffset = LocInfo.second;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000331
Chris Lattnerb88af812009-02-17 07:51:53 +0000332 // Get information about the buffer it points into.
Douglas Gregorf715ca12010-03-16 00:06:06 +0000333 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000334 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
Douglas Gregorf715ca12010-03-16 00:06:06 +0000335 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +0000336 return;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000337
Chris Lattnerb88af812009-02-17 07:51:53 +0000338 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000339 unsigned CaretEndColNo
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000340 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
341
Chris Lattner94f55782009-02-17 07:38:37 +0000342 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000343 const char *TokPtr = BufStart+FileOffset;
344 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000345
346
Chris Lattner94f55782009-02-17 07:38:37 +0000347 // Compute the line end. Scan forward from the error position to the end of
348 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000349 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000350 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000351 ++LineEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000352
Daniel Dunbar06d10722009-10-19 09:11:21 +0000353 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
354 // the source line length as currently being computed. See
355 // test/Misc/message-length.c.
356 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
357
Chris Lattner94f55782009-02-17 07:38:37 +0000358 // Copy the line of code into an std::string for ease of manipulation.
359 std::string SourceLine(LineStart, LineEnd);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000360
Chris Lattner94f55782009-02-17 07:38:37 +0000361 // Create a line for the caret that is filled with spaces that is the same
362 // length as the line of source code.
363 std::string CaretLine(LineEnd-LineStart, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000364
Chris Lattner94f55782009-02-17 07:38:37 +0000365 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000366 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000367 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000368
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000369 for (unsigned i = 0, e = NumRanges; i != e; ++i)
370 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000371 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000372
Chris Lattner94f55782009-02-17 07:38:37 +0000373 // Next, insert the caret itself.
374 if (ColNo-1 < CaretLine.size())
375 CaretLine[ColNo-1] = '^';
376 else
377 CaretLine.push_back('^');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000378
Chris Lattner94f55782009-02-17 07:38:37 +0000379 // Scan the source line, looking for tabs. If we find any, manually expand
Chris Lattner52388f92010-01-13 03:06:50 +0000380 // them to spaces and update the CaretLine to match.
Chris Lattner94f55782009-02-17 07:38:37 +0000381 for (unsigned i = 0; i != SourceLine.size(); ++i) {
382 if (SourceLine[i] != '\t') continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000383
Chris Lattner94f55782009-02-17 07:38:37 +0000384 // Replace this tab with at least one space.
385 SourceLine[i] = ' ';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000386
Chris Lattner94f55782009-02-17 07:38:37 +0000387 // Compute the number of spaces we need to insert.
Chris Lattner52388f92010-01-13 03:06:50 +0000388 unsigned TabStop = DiagOpts->TabStop;
389 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
390 "Invalid -ftabstop value");
Chris Lattner124fca52010-01-09 21:54:33 +0000391 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
392 assert(NumSpaces < TabStop && "Invalid computation of space amt");
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000393
Chris Lattner94f55782009-02-17 07:38:37 +0000394 // Insert spaces into the SourceLine.
395 SourceLine.insert(i+1, NumSpaces, ' ');
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000396
Chris Lattner94f55782009-02-17 07:38:37 +0000397 // Insert spaces or ~'s into CaretLine.
398 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
399 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000400
Chris Lattner770dbf02009-04-28 22:33:16 +0000401 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
402 // produce easily machine parsable output. Add a space before the source line
403 // and the caret to make it trivial to tell the main diagnostic line from what
404 // the user is intended to see.
Daniel Dunbareace8742009-11-04 06:24:30 +0000405 if (DiagOpts->ShowSourceRanges) {
Chris Lattner770dbf02009-04-28 22:33:16 +0000406 SourceLine = ' ' + SourceLine;
407 CaretLine = ' ' + CaretLine;
408 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000409
Douglas Gregor47f71772009-05-01 23:32:58 +0000410 std::string FixItInsertionLine;
Daniel Dunbareace8742009-11-04 06:24:30 +0000411 if (NumHints && DiagOpts->ShowFixits) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000412 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000413 Hint != LastHint; ++Hint) {
414 if (Hint->InsertionLoc.isValid()) {
415 // We have an insertion hint. Determine whether the inserted
416 // code is on the same line as the caret.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000417 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000418 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000419 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
420 SM.getLineNumber(FID, FileOffset)) {
421 // Insert the new code into the line just below the code
422 // that the user wrote.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000423 unsigned HintColNo
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000424 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000425 unsigned LastColumnModified
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000426 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000427 if (LastColumnModified > FixItInsertionLine.size())
428 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000429 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000430 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000431 } else {
432 FixItInsertionLine.clear();
433 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000434 }
435 }
436 }
Douglas Gregore44433c2010-01-18 19:28:01 +0000437 // Now that we have the entire fixit line, expand the tabs in it.
438 // Since we don't want to insert spaces in the middle of a word,
439 // find each word and the column it should line up with and insert
440 // spaces until they match.
441 if (!FixItInsertionLine.empty()) {
442 unsigned FixItPos = 0;
443 unsigned LinePos = 0;
444 unsigned TabExpandedCol = 0;
445 unsigned LineLength = LineEnd - LineStart;
446
447 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
448 // Find the next word in the FixIt line.
449 while (FixItPos < FixItInsertionLine.size() &&
450 FixItInsertionLine[FixItPos] == ' ')
451 ++FixItPos;
452 unsigned CharDistance = FixItPos - TabExpandedCol;
453
454 // Walk forward in the source line, keeping track of
455 // the tab-expanded column.
456 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
457 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
458 ++TabExpandedCol;
459 else
460 TabExpandedCol =
461 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
462
463 // Adjust the fixit line to match this column.
464 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
465 FixItPos = TabExpandedCol;
466
467 // Walk to the end of the word.
468 while (FixItPos < FixItInsertionLine.size() &&
469 FixItInsertionLine[FixItPos] != ' ')
470 ++FixItPos;
471 }
472 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000473 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000474
Douglas Gregor47f71772009-05-01 23:32:58 +0000475 // If the source line is too long for our terminal, select only the
476 // "interesting" source region within that line.
477 if (Columns && SourceLine.size() > Columns)
478 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000479 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000480
Douglas Gregor47f71772009-05-01 23:32:58 +0000481 // Finally, remove any blank spaces from the end of CaretLine.
482 while (CaretLine[CaretLine.size()-1] == ' ')
483 CaretLine.erase(CaretLine.end()-1);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000484
Douglas Gregor47f71772009-05-01 23:32:58 +0000485 // Emit what we have computed.
486 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000487
Daniel Dunbareace8742009-11-04 06:24:30 +0000488 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000489 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000490 OS << CaretLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000491 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000492 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000493
494 if (!FixItInsertionLine.empty()) {
Daniel Dunbareace8742009-11-04 06:24:30 +0000495 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000496 // Print fixit line in color
497 OS.changeColor(fixitColor, false);
Daniel Dunbareace8742009-11-04 06:24:30 +0000498 if (DiagOpts->ShowSourceRanges)
Douglas Gregor47f71772009-05-01 23:32:58 +0000499 OS << ' ';
500 OS << FixItInsertionLine << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000501 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000502 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000503 }
Chris Lattner94f55782009-02-17 07:38:37 +0000504}
505
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000506/// \brief Skip over whitespace in the string, starting at the given
507/// index.
508///
509/// \returns The index of the first non-whitespace character that is
510/// greater than or equal to Idx or, if no such character exists,
511/// returns the end of the string.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000512static unsigned skipWhitespace(unsigned Idx,
Mike Stump1eb44332009-09-09 15:08:12 +0000513 const llvm::SmallVectorImpl<char> &Str,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000514 unsigned Length) {
515 while (Idx < Length && isspace(Str[Idx]))
516 ++Idx;
517 return Idx;
518}
519
520/// \brief If the given character is the start of some kind of
521/// balanced punctuation (e.g., quotes or parentheses), return the
522/// character that will terminate the punctuation.
523///
524/// \returns The ending punctuation character, if any, or the NULL
525/// character if the input character does not start any punctuation.
526static inline char findMatchingPunctuation(char c) {
527 switch (c) {
528 case '\'': return '\'';
529 case '`': return '\'';
530 case '"': return '"';
531 case '(': return ')';
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000532 case '[': return ']';
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000533 case '{': return '}';
534 default: break;
535 }
536
537 return 0;
538}
539
540/// \brief Find the end of the word starting at the given offset
541/// within a string.
542///
543/// \returns the index pointing one character past the end of the
544/// word.
Daniel Dunbareae18f82009-12-06 09:56:18 +0000545static unsigned findEndOfWord(unsigned Start,
546 const llvm::SmallVectorImpl<char> &Str,
547 unsigned Length, unsigned Column,
548 unsigned Columns) {
549 assert(Start < Str.size() && "Invalid start position!");
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000550 unsigned End = Start + 1;
551
Daniel Dunbareae18f82009-12-06 09:56:18 +0000552 // If we are already at the end of the string, take that as the word.
553 if (End == Str.size())
554 return End;
555
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000556 // Determine if the start of the string is actually opening
557 // punctuation, e.g., a quote or parentheses.
558 char EndPunct = findMatchingPunctuation(Str[Start]);
559 if (!EndPunct) {
560 // This is a normal word. Just find the first space character.
561 while (End < Length && !isspace(Str[End]))
562 ++End;
563 return End;
564 }
565
566 // We have the start of a balanced punctuation sequence (quotes,
567 // parentheses, etc.). Determine the full sequence is.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000568 llvm::SmallString<16> PunctuationEndStack;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000569 PunctuationEndStack.push_back(EndPunct);
570 while (End < Length && !PunctuationEndStack.empty()) {
571 if (Str[End] == PunctuationEndStack.back())
572 PunctuationEndStack.pop_back();
573 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
574 PunctuationEndStack.push_back(SubEndPunct);
575
576 ++End;
577 }
578
579 // Find the first space character after the punctuation ended.
580 while (End < Length && !isspace(Str[End]))
581 ++End;
582
583 unsigned PunctWordLength = End - Start;
584 if (// If the word fits on this line
585 Column + PunctWordLength <= Columns ||
586 // ... or the word is "short enough" to take up the next line
587 // without too much ugly white space
588 PunctWordLength < Columns/3)
589 return End; // Take the whole thing as a single "word".
590
591 // The whole quoted/parenthesized string is too long to print as a
592 // single "word". Instead, find the "word" that starts just after
593 // the punctuation and use that end-point instead. This will recurse
594 // until it finds something small enough to consider a word.
595 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
596}
597
598/// \brief Print the given string to a stream, word-wrapping it to
599/// some number of columns in the process.
600///
601/// \brief OS the stream to which the word-wrapping string will be
602/// emitted.
603///
604/// \brief Str the string to word-wrap and output.
605///
606/// \brief Columns the number of columns to word-wrap to.
607///
608/// \brief Column the column number at which the first character of \p
609/// Str will be printed. This will be non-zero when part of the first
610/// line has already been printed.
611///
612/// \brief Indentation the number of spaces to indent any lines beyond
613/// the first line.
614///
615/// \returns true if word-wrapping was required, or false if the
616/// string fit on the first line.
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000617static bool PrintWordWrapped(llvm::raw_ostream &OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000618 const llvm::SmallVectorImpl<char> &Str,
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000619 unsigned Columns,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000620 unsigned Column = 0,
621 unsigned Indentation = WordWrapIndentation) {
622 unsigned Length = Str.size();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000623
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000624 // If there is a newline in this message somewhere, find that
625 // newline and split the message into the part before the newline
626 // (which will be word-wrapped) and the part from the newline one
627 // (which will be emitted unchanged).
628 for (unsigned I = 0; I != Length; ++I)
629 if (Str[I] == '\n') {
630 Length = I;
631 break;
632 }
633
634 // The string used to indent each line.
635 llvm::SmallString<16> IndentStr;
636 IndentStr.assign(Indentation, ' ');
637 bool Wrapped = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000638 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000639 WordStart = WordEnd) {
640 // Find the beginning of the next word.
641 WordStart = skipWhitespace(WordStart, Str, Length);
642 if (WordStart == Length)
643 break;
644
645 // Find the end of this word.
646 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000647
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000648 // Does this word fit on the current line?
649 unsigned WordLength = WordEnd - WordStart;
650 if (Column + WordLength < Columns) {
651 // This word fits on the current line; print it there.
652 if (WordStart) {
653 OS << ' ';
654 Column += 1;
655 }
656 OS.write(&Str[WordStart], WordLength);
657 Column += WordLength;
658 continue;
659 }
660
661 // This word does not fit on the current line, so wrap to the next
662 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000663 OS << '\n';
664 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000665 OS.write(&Str[WordStart], WordLength);
666 Column = Indentation + WordLength;
667 Wrapped = true;
668 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000669
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000670 if (Length == Str.size())
671 return Wrapped; // We're done.
672
673 // There is a newline in the message, followed by something that
674 // will not be word-wrapped. Print that.
675 OS.write(&Str[Length], Str.size() - Length);
676 return true;
677}
Chris Lattner94f55782009-02-17 07:38:37 +0000678
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000679void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
Chris Lattner0a14eee2008-11-18 07:04:44 +0000680 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000681 // Keeps track of the the starting position of the location
682 // information (e.g., "foo.c:10:4:") that precedes the error
683 // message. We use this information to determine how long the
684 // file+line+column number prefix is.
685 uint64_t StartOfLocationInfo = OS.tell();
686
Daniel Dunbarb96b6702010-02-25 03:23:40 +0000687 if (!Prefix.empty())
688 OS << Prefix << ": ";
689
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000690 // If the location is specified, print out a file/line/col and include trace
691 // if enabled.
692 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000693 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000694 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
695 unsigned LineNo = PLoc.getLine();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000696
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // First, if this diagnostic is not in the main file, print out the
698 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000699 if (LastWarningLoc != PLoc.getIncludeLoc()) {
700 LastWarningLoc = PLoc.getIncludeLoc();
701 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000702 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000704
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000705 // Compute the column number.
Daniel Dunbareace8742009-11-04 06:24:30 +0000706 if (DiagOpts->ShowLocation) {
707 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000708 OS.changeColor(savedColor, true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000709
Steve Naroffe0c4d892009-12-05 02:14:08 +0000710 // Emit a Visual Studio compatible line number syntax.
Steve Naroff0304c6c2009-12-05 12:23:07 +0000711 if (LangOpts && LangOpts->Microsoft) {
Steve Naroffe0c4d892009-12-05 02:14:08 +0000712 OS << PLoc.getFilename() << '(' << LineNo << ')';
713 OS << " : ";
714 } else {
715 OS << PLoc.getFilename() << ':' << LineNo << ':';
716 if (DiagOpts->ShowColumn)
717 if (unsigned ColNo = PLoc.getColumn())
718 OS << ColNo << ':';
719 }
Daniel Dunbareace8742009-11-04 06:24:30 +0000720 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000721 FileID CaretFileID =
722 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
723 bool PrintedRange = false;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000724
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000725 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000726 // Ignore invalid ranges.
727 if (!Info.getRange(i).isValid()) continue;
728
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000729 SourceLocation B = Info.getRange(i).getBegin();
730 SourceLocation E = Info.getRange(i).getEnd();
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000731 B = SM.getInstantiationLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000732 E = SM.getInstantiationLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000733
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000734 // If the End location and the start location are the same and are a
735 // macro location, then the range was something that came from a macro
736 // expansion or _Pragma. If this is an object-like macro, the best we
737 // can do is to highlight the range. If this is a function-like
738 // macro, we'd also like to highlight the arguments.
739 if (B == E && Info.getRange(i).getEnd().isMacroID())
740 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
741
742 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000743 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000744
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000745 // If the start or end of the range is in another file, just discard
746 // it.
747 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
748 continue;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000749
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000750 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000751 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000752
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000753 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
754 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
755 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
756 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
757 PrintedRange = true;
758 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000759
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000760 if (PrintedRange)
761 OS << ':';
762 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000763 OS << ' ';
Daniel Dunbareace8742009-11-04 06:24:30 +0000764 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000765 OS.resetColor();
766 }
767 }
768
Daniel Dunbareace8742009-11-04 06:24:30 +0000769 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000770 // Print diagnostic category in bold and color
771 switch (Level) {
772 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
773 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
774 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
775 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
776 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000777 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000779
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000781 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000782 case Diagnostic::Note: OS << "note: "; break;
783 case Diagnostic::Warning: OS << "warning: "; break;
784 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000785 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 }
Torok Edwin603fca72009-06-04 07:18:23 +0000787
Daniel Dunbareace8742009-11-04 06:24:30 +0000788 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000789 OS.resetColor();
790
Chris Lattnerf4c83962008-11-19 06:51:40 +0000791 llvm::SmallString<100> OutStr;
792 Info.FormatDiagnostic(OutStr);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000793
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000794 if (DiagOpts->ShowOptionNames) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000795 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
796 OutStr += " [-W";
797 OutStr += Opt;
798 OutStr += ']';
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000799 } else if (Diagnostic::isBuiltinExtensionDiag(Info.getID())) {
800 OutStr += " [-pedantic]";
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000801 }
Chris Lattner8d2ea4e2010-02-16 18:29:31 +0000802 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000803
Daniel Dunbareace8742009-11-04 06:24:30 +0000804 if (DiagOpts->ShowColors) {
Torok Edwin603fca72009-06-04 07:18:23 +0000805 // Print warnings, errors and fatal errors in bold, no color
806 switch (Level) {
807 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
808 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
809 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
810 default: break; //don't bold notes
811 }
812 }
813
Daniel Dunbareace8742009-11-04 06:24:30 +0000814 if (DiagOpts->MessageLength) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000815 // We will be word-wrapping the error message, so compute the
816 // column number where we currently are (after printing the
817 // location information).
818 unsigned Column = OS.tell() - StartOfLocationInfo;
Daniel Dunbareace8742009-11-04 06:24:30 +0000819 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000820 } else {
821 OS.write(OutStr.begin(), OutStr.size());
822 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000823 OS << '\n';
Daniel Dunbareace8742009-11-04 06:24:30 +0000824 if (DiagOpts->ShowColors)
Torok Edwin603fca72009-06-04 07:18:23 +0000825 OS.resetColor();
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000826
Douglas Gregordf667e72009-03-10 20:44:00 +0000827 // If caret diagnostics are enabled and we have location, we want to
828 // emit the caret. However, we only do this if the location moved
829 // from the last diagnostic, if the last diagnostic was a note that
830 // was part of a different warning or error diagnostic, or if the
831 // diagnostic has ranges. We don't want to emit the same caret
832 // multiple times if one loc has multiple diagnostics.
Daniel Dunbareace8742009-11-04 06:24:30 +0000833 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000834 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000835 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +0000836 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000837 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000838 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000839 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000840
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000841 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000842 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000843 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000844 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000845 for (unsigned i = 0; i != NumRanges; ++i)
846 Ranges[i] = Info.getRange(i);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000847
Douglas Gregor849b2432010-03-31 17:46:05 +0000848 unsigned NumHints = Info.getNumFixItHints();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000849 for (unsigned idx = 0; idx < NumHints; ++idx) {
Douglas Gregor849b2432010-03-31 17:46:05 +0000850 const FixItHint &Hint = Info.getFixItHint(idx);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000851 if (Hint.RemoveRange.isValid()) {
852 assert(NumRanges < 20 && "Out of space");
853 Ranges[NumRanges++] = Hint.RemoveRange;
854 }
855 }
856
857 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000858 Info.getFixItHints(),
859 Info.getNumFixItHints(),
Daniel Dunbareace8742009-11-04 06:24:30 +0000860 DiagOpts->MessageLength);
Reid Spencer5f016e22007-07-11 17:01:13 +0000861 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000862
Chris Lattnera03a5b52008-11-19 06:56:25 +0000863 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000864}