blob: d4c7e0f6f33094b777574e08ca3233ba7094ea3c [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Lex/Lexer.h"
Chris Lattner037fb7f2009-05-05 22:03:18 +000017#include "llvm/Support/MemoryBuffer.h"
Chris Lattnera03a5b52008-11-19 06:56:25 +000018#include "llvm/Support/raw_ostream.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000019#include "llvm/ADT/SmallString.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000020#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000021using namespace clang;
22
Torok Edwin603fca72009-06-04 07:18:23 +000023static const enum llvm::raw_ostream::Colors noteColor =
24 llvm::raw_ostream::BLACK;
25static const enum llvm::raw_ostream::Colors fixitColor =
26 llvm::raw_ostream::GREEN;
27static const enum llvm::raw_ostream::Colors caretColor =
28 llvm::raw_ostream::GREEN;
29static const enum llvm::raw_ostream::Colors warningColor =
30 llvm::raw_ostream::MAGENTA;
31static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
32static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
33// used for changing only the bold attribute
34static const enum llvm::raw_ostream::Colors savedColor =
35 llvm::raw_ostream::SAVEDCOLOR;
36
Douglas Gregorfffd93f2009-05-01 21:53:04 +000037/// \brief Number of spaces to indent when word-wrapping.
38const unsigned WordWrapIndentation = 6;
39
Reid Spencer5f016e22007-07-11 17:01:13 +000040void TextDiagnosticPrinter::
Chris Lattnerb9c3f962009-01-27 07:57:44 +000041PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
42 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000043
Chris Lattnerb9c3f962009-01-27 07:57:44 +000044 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner9dc1f532007-07-20 16:37:10 +000045
Reid Spencer5f016e22007-07-11 17:01:13 +000046 // Print out the other include frames first.
Chris Lattnerb9c3f962009-01-27 07:57:44 +000047 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000048
49 if (ShowLocation)
50 OS << "In file included from " << PLoc.getFilename()
51 << ':' << PLoc.getLine() << ":\n";
52 else
53 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000054}
55
56/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
57/// any characters in LineNo that intersect the SourceRange.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000058void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000059 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000060 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000061 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000062 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000063 assert(CaretLine.size() == SourceLine.size() &&
64 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000065 if (!R.isValid()) return;
66
Chris Lattnerb9c3f962009-01-27 07:57:44 +000067 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
68 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
69
Chris Lattner34837a52009-02-17 05:19:10 +000070 // If the End location and the start location are the same and are a macro
71 // location, then the range was something that came from a macro expansion
72 // or _Pragma. If this is an object-like macro, the best we can do is to
73 // highlight the range. If this is a function-like macro, we'd also like to
74 // highlight the arguments.
75 if (Begin == End && R.getEnd().isMacroID())
76 End = SM.getInstantiationRange(R.getEnd()).second;
77
Chris Lattner30fc9332009-02-04 01:06:56 +000078 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000079 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000080 return; // No intersection.
Reid Spencer5f016e22007-07-11 17:01:13 +000081
Chris Lattner30fc9332009-02-04 01:06:56 +000082 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000083 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000084 return; // No intersection.
Reid Spencer5f016e22007-07-11 17:01:13 +000085
86 // Compute the column number of the start.
87 unsigned StartColNo = 0;
88 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +000089 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +000090 if (StartColNo) --StartColNo; // Zero base the col #.
91 }
92
93 // Pick the first non-whitespace column.
94 while (StartColNo < SourceLine.size() &&
95 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
96 ++StartColNo;
97
98 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +000099 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +0000101 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 if (EndColNo) {
103 --EndColNo; // Zero base the col #.
104
105 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000106 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +0000108 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 }
110 }
111
112 // Pick the last non-whitespace column.
Nuno Lopesdb825682008-08-05 19:40:20 +0000113 if (EndColNo <= SourceLine.size())
114 while (EndColNo-1 &&
115 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
116 --EndColNo;
117 else
118 EndColNo = SourceLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000119
120 // Fill the range with ~'s.
121 assert(StartColNo <= EndColNo && "Invalid range!");
Nuno Lopesdb825682008-08-05 19:40:20 +0000122 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000123 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000124}
125
Douglas Gregor47f71772009-05-01 23:32:58 +0000126/// \brief When the source code line we want to print is too long for
127/// the terminal, select the "interesting" region.
128static void SelectInterestingSourceRegion(std::string &SourceLine,
129 std::string &CaretLine,
130 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000131 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000132 unsigned Columns) {
133 if (CaretLine.size() > SourceLine.size())
134 SourceLine.resize(CaretLine.size(), ' ');
135
136 // Find the slice that we need to display the full caret line
137 // correctly.
138 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
139 for (; CaretStart != CaretEnd; ++CaretStart)
140 if (!isspace(CaretLine[CaretStart]))
141 break;
142
143 for (; CaretEnd != CaretStart; --CaretEnd)
144 if (!isspace(CaretLine[CaretEnd - 1]))
145 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000146
147 // Make sure we don't chop the string shorter than the caret token
148 // itself.
149 if (CaretEnd < EndOfCaretToken)
150 CaretEnd = EndOfCaretToken;
151
Douglas Gregor844da342009-05-03 04:33:32 +0000152 // If we have a fix-it line, make sure the slice includes all of the
153 // fix-it information.
154 if (!FixItInsertionLine.empty()) {
155 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
156 for (; FixItStart != FixItEnd; ++FixItStart)
157 if (!isspace(FixItInsertionLine[FixItStart]))
158 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000159
Douglas Gregor844da342009-05-03 04:33:32 +0000160 for (; FixItEnd != FixItStart; --FixItEnd)
161 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
162 break;
163
164 if (FixItStart < CaretStart)
165 CaretStart = FixItStart;
166 if (FixItEnd > CaretEnd)
167 CaretEnd = FixItEnd;
168 }
169
Douglas Gregor47f71772009-05-01 23:32:58 +0000170 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
171 // parts of the caret line. While this slice is smaller than the
172 // number of columns we have, try to grow the slice to encompass
173 // more context.
174
175 // If the end of the interesting region comes before we run out of
176 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000177 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000178 CaretStart = 0;
179
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000180 unsigned TargetColumns = Columns;
181 if (TargetColumns > 8)
182 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000183 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000184 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000185 bool ExpandedRegion = false;
186 // Move the start of the interesting region left until we've
187 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000188 if (CaretStart == 1)
189 CaretStart = 0;
190 else if (CaretStart > 1) {
191 unsigned NewStart = CaretStart - 1;
Douglas Gregor47f71772009-05-01 23:32:58 +0000192
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000193 // Skip over any whitespace we see here; we're looking for
194 // another bit of interesting text.
195 while (NewStart && isspace(SourceLine[NewStart]))
196 --NewStart;
197
198 // Skip over this bit of "interesting" text.
199 while (NewStart && !isspace(SourceLine[NewStart]))
200 --NewStart;
201
202 // Move up to the non-whitespace character we just saw.
203 if (NewStart)
204 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000205
206 // If we're still within our limit, update the starting
207 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000208 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000209 CaretStart = NewStart;
210 ExpandedRegion = true;
211 }
212 }
213
214 // Move the end of the interesting region right until we've
215 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000216 if (CaretEnd != SourceLength) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000217 unsigned NewEnd = CaretEnd;
218
219 // Skip over any whitespace we see here; we're looking for
220 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000221 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000222 ++NewEnd;
223
224 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000225 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000226 ++NewEnd;
227
228 if (NewEnd - CaretStart <= TargetColumns) {
229 CaretEnd = NewEnd;
230 ExpandedRegion = true;
231 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000232 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000233
234 if (!ExpandedRegion)
235 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000236 }
237
238 // [CaretStart, CaretEnd) is the slice we want. Update the various
239 // output lines to show only this slice, with two-space padding
240 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000241 if (CaretEnd < SourceLine.size())
242 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000243 if (CaretEnd < CaretLine.size())
244 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000245 if (FixItInsertionLine.size() > CaretEnd)
246 FixItInsertionLine.erase(CaretEnd, std::string::npos);
247
248 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000249 SourceLine.replace(0, CaretStart, " ...");
250 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000251 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000252 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000253 }
254}
255
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000256void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner676f0242009-02-20 00:25:28 +0000257 SourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000258 unsigned NumRanges,
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000259 SourceManager &SM,
260 const CodeModificationHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000261 unsigned NumHints,
Douglas Gregor47f71772009-05-01 23:32:58 +0000262 unsigned Columns) {
Chris Lattner55dcef02009-02-17 08:44:50 +0000263 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000264
265 // If this is a macro ID, first emit information about where this was
266 // instantiated (recursively) then emit information about where. the token was
267 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000268 if (!Loc.isFileID()) {
Chris Lattner609b3ab2009-02-18 18:50:45 +0000269 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000270 // FIXME: Map ranges?
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000271 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
Chris Lattner676f0242009-02-20 00:25:28 +0000272
Chris Lattner037fb7f2009-05-05 22:03:18 +0000273 Loc = SM.getImmediateSpellingLoc(Loc);
274
Chris Lattner676f0242009-02-20 00:25:28 +0000275 // Map the ranges.
276 for (unsigned i = 0; i != NumRanges; ++i) {
277 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000278 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
279 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000280 Ranges[i] = SourceRange(S, E);
281 }
Chris Lattner55dcef02009-02-17 08:44:50 +0000282
Chris Lattner5ce24c82009-04-21 03:57:54 +0000283 if (ShowLocation) {
Chris Lattner037fb7f2009-05-05 22:03:18 +0000284 std::pair<FileID, unsigned> IInfo = SM.getDecomposedInstantiationLoc(Loc);
285
Chris Lattner5ce24c82009-04-21 03:57:54 +0000286 // Emit the file/line/column that this expansion came from.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000287 OS << SM.getBuffer(IInfo.first)->getBufferIdentifier() << ':'
288 << SM.getLineNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000289 if (ShowColumn)
Chris Lattner037fb7f2009-05-05 22:03:18 +0000290 OS << SM.getColumnNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000291 OS << ' ';
292 }
293 OS << "note: instantiated from:\n";
Chris Lattner037fb7f2009-05-05 22:03:18 +0000294
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000295 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
Chris Lattner037fb7f2009-05-05 22:03:18 +0000296 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000297 }
Chris Lattnerb88af812009-02-17 07:51:53 +0000298
299 // Decompose the location into a FID/Offset pair.
300 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
301 FileID FID = LocInfo.first;
302 unsigned FileOffset = LocInfo.second;
303
304 // Get information about the buffer it points into.
305 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
306 const char *BufStart = BufferInfo.first;
Chris Lattnerb88af812009-02-17 07:51:53 +0000307
308 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000309 unsigned CaretEndColNo
310 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
311
Chris Lattner94f55782009-02-17 07:38:37 +0000312 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000313 const char *TokPtr = BufStart+FileOffset;
314 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
315
Chris Lattner94f55782009-02-17 07:38:37 +0000316
317 // Compute the line end. Scan forward from the error position to the end of
318 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000319 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000320 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000321 ++LineEnd;
322
323 // Copy the line of code into an std::string for ease of manipulation.
324 std::string SourceLine(LineStart, LineEnd);
325
326 // Create a line for the caret that is filled with spaces that is the same
327 // length as the line of source code.
328 std::string CaretLine(LineEnd-LineStart, ' ');
329
330 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000331 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000332 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
333
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000334 for (unsigned i = 0, e = NumRanges; i != e; ++i)
335 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000336 }
Chris Lattner94f55782009-02-17 07:38:37 +0000337
338 // Next, insert the caret itself.
339 if (ColNo-1 < CaretLine.size())
340 CaretLine[ColNo-1] = '^';
341 else
342 CaretLine.push_back('^');
343
344 // Scan the source line, looking for tabs. If we find any, manually expand
345 // them to 8 characters and update the CaretLine to match.
346 for (unsigned i = 0; i != SourceLine.size(); ++i) {
347 if (SourceLine[i] != '\t') continue;
348
349 // Replace this tab with at least one space.
350 SourceLine[i] = ' ';
351
352 // Compute the number of spaces we need to insert.
353 unsigned NumSpaces = ((i+8)&~7) - (i+1);
354 assert(NumSpaces < 8 && "Invalid computation of space amt");
355
356 // Insert spaces into the SourceLine.
357 SourceLine.insert(i+1, NumSpaces, ' ');
358
359 // Insert spaces or ~'s into CaretLine.
360 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
361 }
362
Chris Lattner770dbf02009-04-28 22:33:16 +0000363 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
364 // produce easily machine parsable output. Add a space before the source line
365 // and the caret to make it trivial to tell the main diagnostic line from what
366 // the user is intended to see.
367 if (PrintRangeInfo) {
368 SourceLine = ' ' + SourceLine;
369 CaretLine = ' ' + CaretLine;
370 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000371
372 std::string FixItInsertionLine;
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000373 if (NumHints && PrintFixItInfo) {
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000374 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000375 Hint != LastHint; ++Hint) {
376 if (Hint->InsertionLoc.isValid()) {
377 // We have an insertion hint. Determine whether the inserted
378 // code is on the same line as the caret.
379 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000380 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000381 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
382 SM.getLineNumber(FID, FileOffset)) {
383 // Insert the new code into the line just below the code
384 // that the user wrote.
385 unsigned HintColNo
386 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
387 unsigned LastColumnModified
388 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000389 if (LastColumnModified > FixItInsertionLine.size())
390 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000391 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000392 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000393 } else {
394 FixItInsertionLine.clear();
395 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000396 }
397 }
398 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000399 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000400
Douglas Gregor47f71772009-05-01 23:32:58 +0000401 // If the source line is too long for our terminal, select only the
402 // "interesting" source region within that line.
403 if (Columns && SourceLine.size() > Columns)
404 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000405 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000406
Douglas Gregor47f71772009-05-01 23:32:58 +0000407 // Finally, remove any blank spaces from the end of CaretLine.
408 while (CaretLine[CaretLine.size()-1] == ' ')
409 CaretLine.erase(CaretLine.end()-1);
410
411 // Emit what we have computed.
412 OS << SourceLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000413
414 if (UseColors)
415 OS.changeColor(caretColor, true);
Douglas Gregor47f71772009-05-01 23:32:58 +0000416 OS << CaretLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000417 if (UseColors)
418 OS.resetColor();
Douglas Gregor47f71772009-05-01 23:32:58 +0000419
420 if (!FixItInsertionLine.empty()) {
Torok Edwin603fca72009-06-04 07:18:23 +0000421 if (UseColors)
422 // Print fixit line in color
423 OS.changeColor(fixitColor, false);
Douglas Gregor47f71772009-05-01 23:32:58 +0000424 if (PrintRangeInfo)
425 OS << ' ';
426 OS << FixItInsertionLine << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000427 if (UseColors)
428 OS.resetColor();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000429 }
Chris Lattner94f55782009-02-17 07:38:37 +0000430}
431
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000432/// \brief Skip over whitespace in the string, starting at the given
433/// index.
434///
435/// \returns The index of the first non-whitespace character that is
436/// greater than or equal to Idx or, if no such character exists,
437/// returns the end of the string.
438static unsigned skipWhitespace(unsigned Idx,
439 const llvm::SmallVectorImpl<char> &Str,
440 unsigned Length) {
441 while (Idx < Length && isspace(Str[Idx]))
442 ++Idx;
443 return Idx;
444}
445
446/// \brief If the given character is the start of some kind of
447/// balanced punctuation (e.g., quotes or parentheses), return the
448/// character that will terminate the punctuation.
449///
450/// \returns The ending punctuation character, if any, or the NULL
451/// character if the input character does not start any punctuation.
452static inline char findMatchingPunctuation(char c) {
453 switch (c) {
454 case '\'': return '\'';
455 case '`': return '\'';
456 case '"': return '"';
457 case '(': return ')';
458 case '[': return ']';
459 case '{': return '}';
460 default: break;
461 }
462
463 return 0;
464}
465
466/// \brief Find the end of the word starting at the given offset
467/// within a string.
468///
469/// \returns the index pointing one character past the end of the
470/// word.
471unsigned findEndOfWord(unsigned Start,
472 const llvm::SmallVectorImpl<char> &Str,
473 unsigned Length, unsigned Column,
474 unsigned Columns) {
475 unsigned End = Start + 1;
476
477 // Determine if the start of the string is actually opening
478 // punctuation, e.g., a quote or parentheses.
479 char EndPunct = findMatchingPunctuation(Str[Start]);
480 if (!EndPunct) {
481 // This is a normal word. Just find the first space character.
482 while (End < Length && !isspace(Str[End]))
483 ++End;
484 return End;
485 }
486
487 // We have the start of a balanced punctuation sequence (quotes,
488 // parentheses, etc.). Determine the full sequence is.
489 llvm::SmallVector<char, 16> PunctuationEndStack;
490 PunctuationEndStack.push_back(EndPunct);
491 while (End < Length && !PunctuationEndStack.empty()) {
492 if (Str[End] == PunctuationEndStack.back())
493 PunctuationEndStack.pop_back();
494 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
495 PunctuationEndStack.push_back(SubEndPunct);
496
497 ++End;
498 }
499
500 // Find the first space character after the punctuation ended.
501 while (End < Length && !isspace(Str[End]))
502 ++End;
503
504 unsigned PunctWordLength = End - Start;
505 if (// If the word fits on this line
506 Column + PunctWordLength <= Columns ||
507 // ... or the word is "short enough" to take up the next line
508 // without too much ugly white space
509 PunctWordLength < Columns/3)
510 return End; // Take the whole thing as a single "word".
511
512 // The whole quoted/parenthesized string is too long to print as a
513 // single "word". Instead, find the "word" that starts just after
514 // the punctuation and use that end-point instead. This will recurse
515 // until it finds something small enough to consider a word.
516 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
517}
518
519/// \brief Print the given string to a stream, word-wrapping it to
520/// some number of columns in the process.
521///
522/// \brief OS the stream to which the word-wrapping string will be
523/// emitted.
524///
525/// \brief Str the string to word-wrap and output.
526///
527/// \brief Columns the number of columns to word-wrap to.
528///
529/// \brief Column the column number at which the first character of \p
530/// Str will be printed. This will be non-zero when part of the first
531/// line has already been printed.
532///
533/// \brief Indentation the number of spaces to indent any lines beyond
534/// the first line.
535///
536/// \returns true if word-wrapping was required, or false if the
537/// string fit on the first line.
538static bool PrintWordWrapped(llvm::raw_ostream &OS,
539 const llvm::SmallVectorImpl<char> &Str,
540 unsigned Columns,
541 unsigned Column = 0,
542 unsigned Indentation = WordWrapIndentation) {
543 unsigned Length = Str.size();
544
545 // If there is a newline in this message somewhere, find that
546 // newline and split the message into the part before the newline
547 // (which will be word-wrapped) and the part from the newline one
548 // (which will be emitted unchanged).
549 for (unsigned I = 0; I != Length; ++I)
550 if (Str[I] == '\n') {
551 Length = I;
552 break;
553 }
554
555 // The string used to indent each line.
556 llvm::SmallString<16> IndentStr;
557 IndentStr.assign(Indentation, ' ');
558 bool Wrapped = false;
559 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
560 WordStart = WordEnd) {
561 // Find the beginning of the next word.
562 WordStart = skipWhitespace(WordStart, Str, Length);
563 if (WordStart == Length)
564 break;
565
566 // Find the end of this word.
567 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
568
569 // Does this word fit on the current line?
570 unsigned WordLength = WordEnd - WordStart;
571 if (Column + WordLength < Columns) {
572 // This word fits on the current line; print it there.
573 if (WordStart) {
574 OS << ' ';
575 Column += 1;
576 }
577 OS.write(&Str[WordStart], WordLength);
578 Column += WordLength;
579 continue;
580 }
581
582 // This word does not fit on the current line, so wrap to the next
583 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000584 OS << '\n';
585 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000586 OS.write(&Str[WordStart], WordLength);
587 Column = Indentation + WordLength;
588 Wrapped = true;
589 }
590
591 if (Length == Str.size())
592 return Wrapped; // We're done.
593
594 // There is a newline in the message, followed by something that
595 // will not be word-wrapped. Print that.
596 OS.write(&Str[Length], Str.size() - Length);
597 return true;
598}
Chris Lattner94f55782009-02-17 07:38:37 +0000599
Chris Lattner0a14eee2008-11-18 07:04:44 +0000600void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
601 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000602 // Keeps track of the the starting position of the location
603 // information (e.g., "foo.c:10:4:") that precedes the error
604 // message. We use this information to determine how long the
605 // file+line+column number prefix is.
606 uint64_t StartOfLocationInfo = OS.tell();
607
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000608 // If the location is specified, print out a file/line/col and include trace
609 // if enabled.
610 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000611 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000612 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
613 unsigned LineNo = PLoc.getLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000614
615 // First, if this diagnostic is not in the main file, print out the
616 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000617 if (LastWarningLoc != PLoc.getIncludeLoc()) {
618 LastWarningLoc = PLoc.getIncludeLoc();
619 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000620 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 }
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000622
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000623 // Compute the column number.
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000624 if (ShowLocation) {
Torok Edwin603fca72009-06-04 07:18:23 +0000625 if (UseColors)
626 OS.changeColor(savedColor, true);
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000627 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattner8f7b3962009-02-17 07:34:34 +0000628 if (ShowColumn)
629 if (unsigned ColNo = PLoc.getColumn())
630 OS << ColNo << ':';
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000631
632 if (PrintRangeInfo && Info.getNumRanges()) {
633 FileID CaretFileID =
634 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
635 bool PrintedRange = false;
636
637 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000638 // Ignore invalid ranges.
639 if (!Info.getRange(i).isValid()) continue;
640
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000641 SourceLocation B = Info.getRange(i).getBegin();
642 SourceLocation E = Info.getRange(i).getEnd();
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000643 B = SM.getInstantiationLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000644 E = SM.getInstantiationLoc(E);
Chris Lattner81ebe9b2009-06-15 05:18:27 +0000645
646 // If the End location and the start location are the same and are a
647 // macro location, then the range was something that came from a macro
648 // expansion or _Pragma. If this is an object-like macro, the best we
649 // can do is to highlight the range. If this is a function-like
650 // macro, we'd also like to highlight the arguments.
651 if (B == E && Info.getRange(i).getEnd().isMacroID())
652 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
653
654 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000655 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
656
657 // If the start or end of the range is in another file, just discard
658 // it.
659 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
660 continue;
661
662 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000663 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000664
665 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
666 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
667 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
668 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
669 PrintedRange = true;
670 }
671
672 if (PrintedRange)
673 OS << ':';
674 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000675 OS << ' ';
Torok Edwin603fca72009-06-04 07:18:23 +0000676 if (UseColors)
677 OS.resetColor();
678 }
679 }
680
681 if (UseColors) {
682 // Print diagnostic category in bold and color
683 switch (Level) {
684 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
685 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
686 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
687 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
688 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000689 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 }
691
692 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000693 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000694 case Diagnostic::Note: OS << "note: "; break;
695 case Diagnostic::Warning: OS << "warning: "; break;
696 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000697 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 }
Torok Edwin603fca72009-06-04 07:18:23 +0000699
700 if (UseColors)
701 OS.resetColor();
702
Chris Lattnerf4c83962008-11-19 06:51:40 +0000703 llvm::SmallString<100> OutStr;
704 Info.FormatDiagnostic(OutStr);
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000705
706 if (PrintDiagnosticOption)
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000707 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
708 OutStr += " [-W";
709 OutStr += Opt;
710 OutStr += ']';
711 }
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000712
Torok Edwin603fca72009-06-04 07:18:23 +0000713 if (UseColors) {
714 // Print warnings, errors and fatal errors in bold, no color
715 switch (Level) {
716 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
717 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
718 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
719 default: break; //don't bold notes
720 }
721 }
722
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000723 if (MessageLength) {
724 // We will be word-wrapping the error message, so compute the
725 // column number where we currently are (after printing the
726 // location information).
727 unsigned Column = OS.tell() - StartOfLocationInfo;
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000728 PrintWordWrapped(OS, OutStr, MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000729 } else {
730 OS.write(OutStr.begin(), OutStr.size());
731 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000732 OS << '\n';
Torok Edwin603fca72009-06-04 07:18:23 +0000733 if (UseColors)
734 OS.resetColor();
Reid Spencer5f016e22007-07-11 17:01:13 +0000735
Douglas Gregordf667e72009-03-10 20:44:00 +0000736 // If caret diagnostics are enabled and we have location, we want to
737 // emit the caret. However, we only do this if the location moved
738 // from the last diagnostic, if the last diagnostic was a note that
739 // was part of a different warning or error diagnostic, or if the
740 // diagnostic has ranges. We don't want to emit the same caret
741 // multiple times if one loc has multiple diagnostics.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000742 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000743 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000744 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000745 Info.getNumCodeModificationHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000746 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000747 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000748 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000749
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000750 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000751 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000752 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000753 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000754 for (unsigned i = 0; i != NumRanges; ++i)
755 Ranges[i] = Info.getRange(i);
756
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000757 unsigned NumHints = Info.getNumCodeModificationHints();
758 for (unsigned idx = 0; idx < NumHints; ++idx) {
759 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
760 if (Hint.RemoveRange.isValid()) {
761 assert(NumRanges < 20 && "Out of space");
762 Ranges[NumRanges++] = Hint.RemoveRange;
763 }
764 }
765
766 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
767 Info.getCodeModificationHints(),
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000768 Info.getNumCodeModificationHints(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000769 MessageLength);
Reid Spencer5f016e22007-07-11 17:01:13 +0000770 }
Chris Lattnera03a5b52008-11-19 06:56:25 +0000771
772 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000773}