blob: 90963c82aca41112f92ab1bf2481d66d88991632 [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
Douglas Gregorfffd93f2009-05-01 21:53:04 +000023/// \brief Number of spaces to indent when word-wrapping.
24const unsigned WordWrapIndentation = 6;
25
Reid Spencer5f016e22007-07-11 17:01:13 +000026void TextDiagnosticPrinter::
Chris Lattnerb9c3f962009-01-27 07:57:44 +000027PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
28 if (Loc.isInvalid()) return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000029
Chris Lattnerb9c3f962009-01-27 07:57:44 +000030 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner9dc1f532007-07-20 16:37:10 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032 // Print out the other include frames first.
Chris Lattnerb9c3f962009-01-27 07:57:44 +000033 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattner5ce24c82009-04-21 03:57:54 +000034
35 if (ShowLocation)
36 OS << "In file included from " << PLoc.getFilename()
37 << ':' << PLoc.getLine() << ":\n";
38 else
39 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000040}
41
42/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
43/// any characters in LineNo that intersect the SourceRange.
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000044void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattnerb9c3f962009-01-27 07:57:44 +000045 const SourceManager &SM,
Chris Lattner3b4d5e92009-01-17 08:45:21 +000046 unsigned LineNo, FileID FID,
Gordon Henriksenaad69532008-08-09 19:58:22 +000047 std::string &CaretLine,
Nuno Lopesdb825682008-08-05 19:40:20 +000048 const std::string &SourceLine) {
Gordon Henriksenaad69532008-08-09 19:58:22 +000049 assert(CaretLine.size() == SourceLine.size() &&
50 "Expect a correspondence between source and caret line!");
Reid Spencer5f016e22007-07-11 17:01:13 +000051 if (!R.isValid()) return;
52
Chris Lattnerb9c3f962009-01-27 07:57:44 +000053 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
54 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
55
Chris Lattner34837a52009-02-17 05:19:10 +000056 // If the End location and the start location are the same and are a macro
57 // location, then the range was something that came from a macro expansion
58 // or _Pragma. If this is an object-like macro, the best we can do is to
59 // highlight the range. If this is a function-like macro, we'd also like to
60 // highlight the arguments.
61 if (Begin == End && R.getEnd().isMacroID())
62 End = SM.getInstantiationRange(R.getEnd()).second;
63
Chris Lattner30fc9332009-02-04 01:06:56 +000064 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000065 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000066 return; // No intersection.
Reid Spencer5f016e22007-07-11 17:01:13 +000067
Chris Lattner30fc9332009-02-04 01:06:56 +000068 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattnerb9c3f962009-01-27 07:57:44 +000069 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnere41b7cd2008-01-12 06:43:35 +000070 return; // No intersection.
Reid Spencer5f016e22007-07-11 17:01:13 +000071
72 // Compute the column number of the start.
73 unsigned StartColNo = 0;
74 if (StartLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +000075 StartColNo = SM.getInstantiationColumnNumber(Begin);
Reid Spencer5f016e22007-07-11 17:01:13 +000076 if (StartColNo) --StartColNo; // Zero base the col #.
77 }
78
79 // Pick the first non-whitespace column.
80 while (StartColNo < SourceLine.size() &&
81 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
82 ++StartColNo;
83
84 // Compute the column number of the end.
Gordon Henriksenaad69532008-08-09 19:58:22 +000085 unsigned EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +000086 if (EndLineNo == LineNo) {
Chris Lattner7da5aea2009-02-04 00:55:58 +000087 EndColNo = SM.getInstantiationColumnNumber(End);
Reid Spencer5f016e22007-07-11 17:01:13 +000088 if (EndColNo) {
89 --EndColNo; // Zero base the col #.
90
91 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +000092 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Reid Spencer5f016e22007-07-11 17:01:13 +000093 } else {
Gordon Henriksenaad69532008-08-09 19:58:22 +000094 EndColNo = CaretLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +000095 }
96 }
97
98 // Pick the last non-whitespace column.
Nuno Lopesdb825682008-08-05 19:40:20 +000099 if (EndColNo <= SourceLine.size())
100 while (EndColNo-1 &&
101 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
102 --EndColNo;
103 else
104 EndColNo = SourceLine.size();
Reid Spencer5f016e22007-07-11 17:01:13 +0000105
106 // Fill the range with ~'s.
107 assert(StartColNo <= EndColNo && "Invalid range!");
Nuno Lopesdb825682008-08-05 19:40:20 +0000108 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenaad69532008-08-09 19:58:22 +0000109 CaretLine[i] = '~';
Reid Spencer5f016e22007-07-11 17:01:13 +0000110}
111
Douglas Gregor47f71772009-05-01 23:32:58 +0000112/// \brief When the source code line we want to print is too long for
113/// the terminal, select the "interesting" region.
114static void SelectInterestingSourceRegion(std::string &SourceLine,
115 std::string &CaretLine,
116 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000117 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000118 unsigned Columns) {
119 if (CaretLine.size() > SourceLine.size())
120 SourceLine.resize(CaretLine.size(), ' ');
121
122 // Find the slice that we need to display the full caret line
123 // correctly.
124 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
125 for (; CaretStart != CaretEnd; ++CaretStart)
126 if (!isspace(CaretLine[CaretStart]))
127 break;
128
129 for (; CaretEnd != CaretStart; --CaretEnd)
130 if (!isspace(CaretLine[CaretEnd - 1]))
131 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000132
133 // Make sure we don't chop the string shorter than the caret token
134 // itself.
135 if (CaretEnd < EndOfCaretToken)
136 CaretEnd = EndOfCaretToken;
137
Douglas Gregor844da342009-05-03 04:33:32 +0000138 // If we have a fix-it line, make sure the slice includes all of the
139 // fix-it information.
140 if (!FixItInsertionLine.empty()) {
141 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
142 for (; FixItStart != FixItEnd; ++FixItStart)
143 if (!isspace(FixItInsertionLine[FixItStart]))
144 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000145
Douglas Gregor844da342009-05-03 04:33:32 +0000146 for (; FixItEnd != FixItStart; --FixItEnd)
147 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
148 break;
149
150 if (FixItStart < CaretStart)
151 CaretStart = FixItStart;
152 if (FixItEnd > CaretEnd)
153 CaretEnd = FixItEnd;
154 }
155
Douglas Gregor47f71772009-05-01 23:32:58 +0000156 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
157 // parts of the caret line. While this slice is smaller than the
158 // number of columns we have, try to grow the slice to encompass
159 // more context.
160
161 // If the end of the interesting region comes before we run out of
162 // space in the terminal, start at the beginning of the line.
Douglas Gregor2167de42009-05-03 15:24:25 +0000163 if (CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000164 CaretStart = 0;
165
Douglas Gregor7d101f62009-05-03 04:12:51 +0000166 unsigned TargetColumns = Columns - 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000167 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000168 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000169 bool ExpandedRegion = false;
170 // Move the start of the interesting region left until we've
171 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000172 if (CaretStart == 1)
173 CaretStart = 0;
174 else if (CaretStart > 1) {
175 unsigned NewStart = CaretStart - 1;
Douglas Gregor47f71772009-05-01 23:32:58 +0000176
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000177 // Skip over any whitespace we see here; we're looking for
178 // another bit of interesting text.
179 while (NewStart && isspace(SourceLine[NewStart]))
180 --NewStart;
181
182 // Skip over this bit of "interesting" text.
183 while (NewStart && !isspace(SourceLine[NewStart]))
184 --NewStart;
185
186 // Move up to the non-whitespace character we just saw.
187 if (NewStart)
188 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000189
190 // If we're still within our limit, update the starting
191 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000192 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000193 CaretStart = NewStart;
194 ExpandedRegion = true;
195 }
196 }
197
198 // Move the end of the interesting region right until we've
199 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000200 if (CaretEnd != SourceLength) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000201 unsigned NewEnd = CaretEnd;
202
203 // Skip over any whitespace we see here; we're looking for
204 // another bit of interesting text.
205 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
206 ++NewEnd;
207
208 // Skip over this bit of "interesting" text.
209 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
210 ++NewEnd;
211
212 if (NewEnd - CaretStart <= TargetColumns) {
213 CaretEnd = NewEnd;
214 ExpandedRegion = true;
215 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000216 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000217
218 if (!ExpandedRegion)
219 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000220 }
221
222 // [CaretStart, CaretEnd) is the slice we want. Update the various
223 // output lines to show only this slice, with two-space padding
224 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000225 if (CaretEnd < SourceLine.size())
226 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000227 if (CaretEnd < CaretLine.size())
228 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000229 if (FixItInsertionLine.size() > CaretEnd)
230 FixItInsertionLine.erase(CaretEnd, std::string::npos);
231
232 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000233 SourceLine.replace(0, CaretStart, " ...");
234 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000235 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000236 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000237 }
238}
239
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000240void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner676f0242009-02-20 00:25:28 +0000241 SourceRange *Ranges,
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000242 unsigned NumRanges,
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000243 SourceManager &SM,
244 const CodeModificationHint *Hints,
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000245 unsigned NumHints,
Douglas Gregor47f71772009-05-01 23:32:58 +0000246 unsigned AvoidColumn,
247 unsigned Columns) {
Chris Lattner55dcef02009-02-17 08:44:50 +0000248 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000249
250 // If this is a macro ID, first emit information about where this was
251 // instantiated (recursively) then emit information about where. the token was
252 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000253 if (!Loc.isFileID()) {
Chris Lattner609b3ab2009-02-18 18:50:45 +0000254 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000255 // FIXME: Map ranges?
Douglas Gregor47f71772009-05-01 23:32:58 +0000256 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
257 Columns);
Chris Lattner676f0242009-02-20 00:25:28 +0000258
Chris Lattner037fb7f2009-05-05 22:03:18 +0000259 Loc = SM.getImmediateSpellingLoc(Loc);
260
Chris Lattner676f0242009-02-20 00:25:28 +0000261 // Map the ranges.
262 for (unsigned i = 0; i != NumRanges; ++i) {
263 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000264 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
265 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000266 Ranges[i] = SourceRange(S, E);
267 }
Chris Lattner55dcef02009-02-17 08:44:50 +0000268
Chris Lattner5ce24c82009-04-21 03:57:54 +0000269 if (ShowLocation) {
Chris Lattner037fb7f2009-05-05 22:03:18 +0000270 std::pair<FileID, unsigned> IInfo = SM.getDecomposedInstantiationLoc(Loc);
271
Chris Lattner5ce24c82009-04-21 03:57:54 +0000272 // Emit the file/line/column that this expansion came from.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000273 OS << SM.getBuffer(IInfo.first)->getBufferIdentifier() << ':'
274 << SM.getLineNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000275 if (ShowColumn)
Chris Lattner037fb7f2009-05-05 22:03:18 +0000276 OS << SM.getColumnNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000277 OS << ' ';
278 }
279 OS << "note: instantiated from:\n";
Chris Lattner037fb7f2009-05-05 22:03:18 +0000280
281 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, 0,Columns);
282 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000283 }
Chris Lattnerb88af812009-02-17 07:51:53 +0000284
285 // Decompose the location into a FID/Offset pair.
286 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
287 FileID FID = LocInfo.first;
288 unsigned FileOffset = LocInfo.second;
289
290 // Get information about the buffer it points into.
291 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
292 const char *BufStart = BufferInfo.first;
Chris Lattnerb88af812009-02-17 07:51:53 +0000293
294 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000295 unsigned CaretEndColNo
296 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
297
Chris Lattner94f55782009-02-17 07:38:37 +0000298 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000299 const char *TokPtr = BufStart+FileOffset;
300 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
301
Chris Lattner94f55782009-02-17 07:38:37 +0000302
303 // Compute the line end. Scan forward from the error position to the end of
304 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000305 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000306 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000307 ++LineEnd;
308
309 // Copy the line of code into an std::string for ease of manipulation.
310 std::string SourceLine(LineStart, LineEnd);
311
312 // Create a line for the caret that is filled with spaces that is the same
313 // length as the line of source code.
314 std::string CaretLine(LineEnd-LineStart, ' ');
315
316 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000317 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000318 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
319
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000320 for (unsigned i = 0, e = NumRanges; i != e; ++i)
321 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000322 }
Chris Lattner94f55782009-02-17 07:38:37 +0000323
324 // Next, insert the caret itself.
325 if (ColNo-1 < CaretLine.size())
326 CaretLine[ColNo-1] = '^';
327 else
328 CaretLine.push_back('^');
329
330 // Scan the source line, looking for tabs. If we find any, manually expand
331 // them to 8 characters and update the CaretLine to match.
332 for (unsigned i = 0; i != SourceLine.size(); ++i) {
333 if (SourceLine[i] != '\t') continue;
334
335 // Replace this tab with at least one space.
336 SourceLine[i] = ' ';
337
338 // Compute the number of spaces we need to insert.
339 unsigned NumSpaces = ((i+8)&~7) - (i+1);
340 assert(NumSpaces < 8 && "Invalid computation of space amt");
341
342 // Insert spaces into the SourceLine.
343 SourceLine.insert(i+1, NumSpaces, ' ');
344
345 // Insert spaces or ~'s into CaretLine.
346 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
347 }
348
Chris Lattner770dbf02009-04-28 22:33:16 +0000349 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
350 // produce easily machine parsable output. Add a space before the source line
351 // and the caret to make it trivial to tell the main diagnostic line from what
352 // the user is intended to see.
353 if (PrintRangeInfo) {
354 SourceLine = ' ' + SourceLine;
355 CaretLine = ' ' + CaretLine;
356 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000357
358 std::string FixItInsertionLine;
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000359 if (NumHints && PrintFixItInfo) {
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000360 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000361 Hint != LastHint; ++Hint) {
362 if (Hint->InsertionLoc.isValid()) {
363 // We have an insertion hint. Determine whether the inserted
364 // code is on the same line as the caret.
365 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000366 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000367 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
368 SM.getLineNumber(FID, FileOffset)) {
369 // Insert the new code into the line just below the code
370 // that the user wrote.
371 unsigned HintColNo
372 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
373 unsigned LastColumnModified
374 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000375 if (LastColumnModified > FixItInsertionLine.size())
376 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000377 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000378 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000379 } else {
380 FixItInsertionLine.clear();
381 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000382 }
383 }
384 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000385 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000386
Douglas Gregor47f71772009-05-01 23:32:58 +0000387 // If the source line is too long for our terminal, select only the
388 // "interesting" source region within that line.
389 if (Columns && SourceLine.size() > Columns)
390 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000391 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000392
393 // AvoidColumn tells us which column we should avoid when printing
394 // the source line. If the source line would start at or near that
395 // column, add another line of whitespace before printing the source
396 // line. Otherwise, the source line and the diagnostic text can get
397 // jumbled together.
398 unsigned StartCol = 0;
399 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
400 if (!isspace(SourceLine[StartCol]))
401 break;
402
403 if (StartCol != SourceLine.size() &&
404 abs((int)StartCol - (int)AvoidColumn) <= 2)
405 OS << '\n';
406
407 // 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';
413 OS << CaretLine << '\n';
414
415 if (!FixItInsertionLine.empty()) {
416 if (PrintRangeInfo)
417 OS << ' ';
418 OS << FixItInsertionLine << '\n';
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000419 }
Chris Lattner94f55782009-02-17 07:38:37 +0000420}
421
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000422/// \brief Skip over whitespace in the string, starting at the given
423/// index.
424///
425/// \returns The index of the first non-whitespace character that is
426/// greater than or equal to Idx or, if no such character exists,
427/// returns the end of the string.
428static unsigned skipWhitespace(unsigned Idx,
429 const llvm::SmallVectorImpl<char> &Str,
430 unsigned Length) {
431 while (Idx < Length && isspace(Str[Idx]))
432 ++Idx;
433 return Idx;
434}
435
436/// \brief If the given character is the start of some kind of
437/// balanced punctuation (e.g., quotes or parentheses), return the
438/// character that will terminate the punctuation.
439///
440/// \returns The ending punctuation character, if any, or the NULL
441/// character if the input character does not start any punctuation.
442static inline char findMatchingPunctuation(char c) {
443 switch (c) {
444 case '\'': return '\'';
445 case '`': return '\'';
446 case '"': return '"';
447 case '(': return ')';
448 case '[': return ']';
449 case '{': return '}';
450 default: break;
451 }
452
453 return 0;
454}
455
456/// \brief Find the end of the word starting at the given offset
457/// within a string.
458///
459/// \returns the index pointing one character past the end of the
460/// word.
461unsigned findEndOfWord(unsigned Start,
462 const llvm::SmallVectorImpl<char> &Str,
463 unsigned Length, unsigned Column,
464 unsigned Columns) {
465 unsigned End = Start + 1;
466
467 // Determine if the start of the string is actually opening
468 // punctuation, e.g., a quote or parentheses.
469 char EndPunct = findMatchingPunctuation(Str[Start]);
470 if (!EndPunct) {
471 // This is a normal word. Just find the first space character.
472 while (End < Length && !isspace(Str[End]))
473 ++End;
474 return End;
475 }
476
477 // We have the start of a balanced punctuation sequence (quotes,
478 // parentheses, etc.). Determine the full sequence is.
479 llvm::SmallVector<char, 16> PunctuationEndStack;
480 PunctuationEndStack.push_back(EndPunct);
481 while (End < Length && !PunctuationEndStack.empty()) {
482 if (Str[End] == PunctuationEndStack.back())
483 PunctuationEndStack.pop_back();
484 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
485 PunctuationEndStack.push_back(SubEndPunct);
486
487 ++End;
488 }
489
490 // Find the first space character after the punctuation ended.
491 while (End < Length && !isspace(Str[End]))
492 ++End;
493
494 unsigned PunctWordLength = End - Start;
495 if (// If the word fits on this line
496 Column + PunctWordLength <= Columns ||
497 // ... or the word is "short enough" to take up the next line
498 // without too much ugly white space
499 PunctWordLength < Columns/3)
500 return End; // Take the whole thing as a single "word".
501
502 // The whole quoted/parenthesized string is too long to print as a
503 // single "word". Instead, find the "word" that starts just after
504 // the punctuation and use that end-point instead. This will recurse
505 // until it finds something small enough to consider a word.
506 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
507}
508
509/// \brief Print the given string to a stream, word-wrapping it to
510/// some number of columns in the process.
511///
512/// \brief OS the stream to which the word-wrapping string will be
513/// emitted.
514///
515/// \brief Str the string to word-wrap and output.
516///
517/// \brief Columns the number of columns to word-wrap to.
518///
519/// \brief Column the column number at which the first character of \p
520/// Str will be printed. This will be non-zero when part of the first
521/// line has already been printed.
522///
523/// \brief Indentation the number of spaces to indent any lines beyond
524/// the first line.
525///
526/// \returns true if word-wrapping was required, or false if the
527/// string fit on the first line.
528static bool PrintWordWrapped(llvm::raw_ostream &OS,
529 const llvm::SmallVectorImpl<char> &Str,
530 unsigned Columns,
531 unsigned Column = 0,
532 unsigned Indentation = WordWrapIndentation) {
533 unsigned Length = Str.size();
534
535 // If there is a newline in this message somewhere, find that
536 // newline and split the message into the part before the newline
537 // (which will be word-wrapped) and the part from the newline one
538 // (which will be emitted unchanged).
539 for (unsigned I = 0; I != Length; ++I)
540 if (Str[I] == '\n') {
541 Length = I;
542 break;
543 }
544
545 // The string used to indent each line.
546 llvm::SmallString<16> IndentStr;
547 IndentStr.assign(Indentation, ' ');
548 bool Wrapped = false;
549 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
550 WordStart = WordEnd) {
551 // Find the beginning of the next word.
552 WordStart = skipWhitespace(WordStart, Str, Length);
553 if (WordStart == Length)
554 break;
555
556 // Find the end of this word.
557 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
558
559 // Does this word fit on the current line?
560 unsigned WordLength = WordEnd - WordStart;
561 if (Column + WordLength < Columns) {
562 // This word fits on the current line; print it there.
563 if (WordStart) {
564 OS << ' ';
565 Column += 1;
566 }
567 OS.write(&Str[WordStart], WordLength);
568 Column += WordLength;
569 continue;
570 }
571
572 // This word does not fit on the current line, so wrap to the next
573 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000574 OS << '\n';
575 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000576 OS.write(&Str[WordStart], WordLength);
577 Column = Indentation + WordLength;
578 Wrapped = true;
579 }
580
581 if (Length == Str.size())
582 return Wrapped; // We're done.
583
584 // There is a newline in the message, followed by something that
585 // will not be word-wrapped. Print that.
586 OS.write(&Str[Length], Str.size() - Length);
587 return true;
588}
Chris Lattner94f55782009-02-17 07:38:37 +0000589
Chris Lattner0a14eee2008-11-18 07:04:44 +0000590void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
591 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000592 // Keeps track of the the starting position of the location
593 // information (e.g., "foo.c:10:4:") that precedes the error
594 // message. We use this information to determine how long the
595 // file+line+column number prefix is.
596 uint64_t StartOfLocationInfo = OS.tell();
597
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000598 // If the location is specified, print out a file/line/col and include trace
599 // if enabled.
600 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000601 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000602 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
603 unsigned LineNo = PLoc.getLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000604
605 // First, if this diagnostic is not in the main file, print out the
606 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000607 if (LastWarningLoc != PLoc.getIncludeLoc()) {
608 LastWarningLoc = PLoc.getIncludeLoc();
609 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000610 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 }
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000612
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000613 // Compute the column number.
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000614 if (ShowLocation) {
615 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattner8f7b3962009-02-17 07:34:34 +0000616 if (ShowColumn)
617 if (unsigned ColNo = PLoc.getColumn())
618 OS << ColNo << ':';
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000619
620 if (PrintRangeInfo && Info.getNumRanges()) {
621 FileID CaretFileID =
622 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
623 bool PrintedRange = false;
624
625 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000626 // Ignore invalid ranges.
627 if (!Info.getRange(i).isValid()) continue;
628
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000629 SourceLocation B = Info.getRange(i).getBegin();
630 SourceLocation E = Info.getRange(i).getEnd();
631 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
632
633 E = SM.getInstantiationLoc(E);
634 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
635
636 // If the start or end of the range is in another file, just discard
637 // it.
638 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
639 continue;
640
641 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000642 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000643
644 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
645 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
646 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
647 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
648 PrintedRange = true;
649 }
650
651 if (PrintedRange)
652 OS << ':';
653 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000654 OS << ' ';
655 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 }
657
658 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000659 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000660 case Diagnostic::Note: OS << "note: "; break;
661 case Diagnostic::Warning: OS << "warning: "; break;
662 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000663 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 }
665
Chris Lattnerf4c83962008-11-19 06:51:40 +0000666 llvm::SmallString<100> OutStr;
667 Info.FormatDiagnostic(OutStr);
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000668
669 if (PrintDiagnosticOption)
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000670 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
671 OutStr += " [-W";
672 OutStr += Opt;
673 OutStr += ']';
674 }
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000675
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000676 bool WordWrapped = false;
677 if (MessageLength) {
678 // We will be word-wrapping the error message, so compute the
679 // column number where we currently are (after printing the
680 // location information).
681 unsigned Column = OS.tell() - StartOfLocationInfo;
682 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
683 } else {
684 OS.write(OutStr.begin(), OutStr.size());
685 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000686 OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000687
Douglas Gregordf667e72009-03-10 20:44:00 +0000688 // If caret diagnostics are enabled and we have location, we want to
689 // emit the caret. However, we only do this if the location moved
690 // from the last diagnostic, if the last diagnostic was a note that
691 // was part of a different warning or error diagnostic, or if the
692 // diagnostic has ranges. We don't want to emit the same caret
693 // multiple times if one loc has multiple diagnostics.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000694 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000695 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000696 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000697 Info.getNumCodeModificationHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000698 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000699 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000700 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000701
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000702 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000703 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000704 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000705 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000706 for (unsigned i = 0; i != NumRanges; ++i)
707 Ranges[i] = Info.getRange(i);
708
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000709 unsigned NumHints = Info.getNumCodeModificationHints();
710 for (unsigned idx = 0; idx < NumHints; ++idx) {
711 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
712 if (Hint.RemoveRange.isValid()) {
713 assert(NumRanges < 20 && "Out of space");
714 Ranges[NumRanges++] = Hint.RemoveRange;
715 }
716 }
717
718 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
719 Info.getCodeModificationHints(),
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000720 Info.getNumCodeModificationHints(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000721 WordWrapped? WordWrapIndentation : 0,
722 MessageLength);
Reid Spencer5f016e22007-07-11 17:01:13 +0000723 }
Chris Lattnera03a5b52008-11-19 06:56:25 +0000724
725 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000726}