blob: f936807b6cfc135fc5033c8c0c0ca11965f62673 [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 Columns) {
Chris Lattner55dcef02009-02-17 08:44:50 +0000247 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner037fb7f2009-05-05 22:03:18 +0000248
249 // If this is a macro ID, first emit information about where this was
250 // instantiated (recursively) then emit information about where. the token was
251 // spelled from.
Chris Lattner55dcef02009-02-17 08:44:50 +0000252 if (!Loc.isFileID()) {
Chris Lattner609b3ab2009-02-18 18:50:45 +0000253 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner037fb7f2009-05-05 22:03:18 +0000254 // FIXME: Map ranges?
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000255 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
Chris Lattner676f0242009-02-20 00:25:28 +0000256
Chris Lattner037fb7f2009-05-05 22:03:18 +0000257 Loc = SM.getImmediateSpellingLoc(Loc);
258
Chris Lattner676f0242009-02-20 00:25:28 +0000259 // Map the ranges.
260 for (unsigned i = 0; i != NumRanges; ++i) {
261 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
Chris Lattner037fb7f2009-05-05 22:03:18 +0000262 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
263 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner676f0242009-02-20 00:25:28 +0000264 Ranges[i] = SourceRange(S, E);
265 }
Chris Lattner55dcef02009-02-17 08:44:50 +0000266
Chris Lattner5ce24c82009-04-21 03:57:54 +0000267 if (ShowLocation) {
Chris Lattner037fb7f2009-05-05 22:03:18 +0000268 std::pair<FileID, unsigned> IInfo = SM.getDecomposedInstantiationLoc(Loc);
269
Chris Lattner5ce24c82009-04-21 03:57:54 +0000270 // Emit the file/line/column that this expansion came from.
Chris Lattner037fb7f2009-05-05 22:03:18 +0000271 OS << SM.getBuffer(IInfo.first)->getBufferIdentifier() << ':'
272 << SM.getLineNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000273 if (ShowColumn)
Chris Lattner037fb7f2009-05-05 22:03:18 +0000274 OS << SM.getColumnNumber(IInfo.first, IInfo.second) << ':';
Chris Lattner5ce24c82009-04-21 03:57:54 +0000275 OS << ' ';
276 }
277 OS << "note: instantiated from:\n";
Chris Lattner037fb7f2009-05-05 22:03:18 +0000278
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000279 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
Chris Lattner037fb7f2009-05-05 22:03:18 +0000280 return;
Chris Lattner55dcef02009-02-17 08:44:50 +0000281 }
Chris Lattnerb88af812009-02-17 07:51:53 +0000282
283 // Decompose the location into a FID/Offset pair.
284 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
285 FileID FID = LocInfo.first;
286 unsigned FileOffset = LocInfo.second;
287
288 // Get information about the buffer it points into.
289 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
290 const char *BufStart = BufferInfo.first;
Chris Lattnerb88af812009-02-17 07:51:53 +0000291
292 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000293 unsigned CaretEndColNo
294 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
295
Chris Lattner94f55782009-02-17 07:38:37 +0000296 // Rewind from the current position to the start of the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000297 const char *TokPtr = BufStart+FileOffset;
298 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
299
Chris Lattner94f55782009-02-17 07:38:37 +0000300
301 // Compute the line end. Scan forward from the error position to the end of
302 // the line.
Chris Lattnerb88af812009-02-17 07:51:53 +0000303 const char *LineEnd = TokPtr;
Chris Lattnercd1148b2009-03-08 08:11:22 +0000304 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattner94f55782009-02-17 07:38:37 +0000305 ++LineEnd;
306
307 // Copy the line of code into an std::string for ease of manipulation.
308 std::string SourceLine(LineStart, LineEnd);
309
310 // Create a line for the caret that is filled with spaces that is the same
311 // length as the line of source code.
312 std::string CaretLine(LineEnd-LineStart, ' ');
313
314 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000315 if (NumRanges) {
Chris Lattnerb88af812009-02-17 07:51:53 +0000316 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
317
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000318 for (unsigned i = 0, e = NumRanges; i != e; ++i)
319 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattnerb88af812009-02-17 07:51:53 +0000320 }
Chris Lattner94f55782009-02-17 07:38:37 +0000321
322 // Next, insert the caret itself.
323 if (ColNo-1 < CaretLine.size())
324 CaretLine[ColNo-1] = '^';
325 else
326 CaretLine.push_back('^');
327
328 // Scan the source line, looking for tabs. If we find any, manually expand
329 // them to 8 characters and update the CaretLine to match.
330 for (unsigned i = 0; i != SourceLine.size(); ++i) {
331 if (SourceLine[i] != '\t') continue;
332
333 // Replace this tab with at least one space.
334 SourceLine[i] = ' ';
335
336 // Compute the number of spaces we need to insert.
337 unsigned NumSpaces = ((i+8)&~7) - (i+1);
338 assert(NumSpaces < 8 && "Invalid computation of space amt");
339
340 // Insert spaces into the SourceLine.
341 SourceLine.insert(i+1, NumSpaces, ' ');
342
343 // Insert spaces or ~'s into CaretLine.
344 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
345 }
346
Chris Lattner770dbf02009-04-28 22:33:16 +0000347 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
348 // produce easily machine parsable output. Add a space before the source line
349 // and the caret to make it trivial to tell the main diagnostic line from what
350 // the user is intended to see.
351 if (PrintRangeInfo) {
352 SourceLine = ' ' + SourceLine;
353 CaretLine = ' ' + CaretLine;
354 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000355
356 std::string FixItInsertionLine;
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000357 if (NumHints && PrintFixItInfo) {
Chris Lattneraa5bf2e2009-04-19 07:44:08 +0000358 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000359 Hint != LastHint; ++Hint) {
360 if (Hint->InsertionLoc.isValid()) {
361 // We have an insertion hint. Determine whether the inserted
362 // code is on the same line as the caret.
363 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner7b5b5b42009-03-02 20:58:48 +0000364 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000365 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
366 SM.getLineNumber(FID, FileOffset)) {
367 // Insert the new code into the line just below the code
368 // that the user wrote.
369 unsigned HintColNo
370 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
371 unsigned LastColumnModified
372 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregor47f71772009-05-01 23:32:58 +0000373 if (LastColumnModified > FixItInsertionLine.size())
374 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000375 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000376 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor844da342009-05-03 04:33:32 +0000377 } else {
378 FixItInsertionLine.clear();
379 break;
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000380 }
381 }
382 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000383 }
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000384
Douglas Gregor47f71772009-05-01 23:32:58 +0000385 // If the source line is too long for our terminal, select only the
386 // "interesting" source region within that line.
387 if (Columns && SourceLine.size() > Columns)
388 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000389 CaretEndColNo, Columns);
Douglas Gregor47f71772009-05-01 23:32:58 +0000390
Douglas Gregor47f71772009-05-01 23:32:58 +0000391 // Finally, remove any blank spaces from the end of CaretLine.
392 while (CaretLine[CaretLine.size()-1] == ' ')
393 CaretLine.erase(CaretLine.end()-1);
394
395 // Emit what we have computed.
396 OS << SourceLine << '\n';
397 OS << CaretLine << '\n';
398
399 if (!FixItInsertionLine.empty()) {
400 if (PrintRangeInfo)
401 OS << ' ';
402 OS << FixItInsertionLine << '\n';
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000403 }
Chris Lattner94f55782009-02-17 07:38:37 +0000404}
405
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000406/// \brief Skip over whitespace in the string, starting at the given
407/// index.
408///
409/// \returns The index of the first non-whitespace character that is
410/// greater than or equal to Idx or, if no such character exists,
411/// returns the end of the string.
412static unsigned skipWhitespace(unsigned Idx,
413 const llvm::SmallVectorImpl<char> &Str,
414 unsigned Length) {
415 while (Idx < Length && isspace(Str[Idx]))
416 ++Idx;
417 return Idx;
418}
419
420/// \brief If the given character is the start of some kind of
421/// balanced punctuation (e.g., quotes or parentheses), return the
422/// character that will terminate the punctuation.
423///
424/// \returns The ending punctuation character, if any, or the NULL
425/// character if the input character does not start any punctuation.
426static inline char findMatchingPunctuation(char c) {
427 switch (c) {
428 case '\'': return '\'';
429 case '`': return '\'';
430 case '"': return '"';
431 case '(': return ')';
432 case '[': return ']';
433 case '{': return '}';
434 default: break;
435 }
436
437 return 0;
438}
439
440/// \brief Find the end of the word starting at the given offset
441/// within a string.
442///
443/// \returns the index pointing one character past the end of the
444/// word.
445unsigned findEndOfWord(unsigned Start,
446 const llvm::SmallVectorImpl<char> &Str,
447 unsigned Length, unsigned Column,
448 unsigned Columns) {
449 unsigned End = Start + 1;
450
451 // Determine if the start of the string is actually opening
452 // punctuation, e.g., a quote or parentheses.
453 char EndPunct = findMatchingPunctuation(Str[Start]);
454 if (!EndPunct) {
455 // This is a normal word. Just find the first space character.
456 while (End < Length && !isspace(Str[End]))
457 ++End;
458 return End;
459 }
460
461 // We have the start of a balanced punctuation sequence (quotes,
462 // parentheses, etc.). Determine the full sequence is.
463 llvm::SmallVector<char, 16> PunctuationEndStack;
464 PunctuationEndStack.push_back(EndPunct);
465 while (End < Length && !PunctuationEndStack.empty()) {
466 if (Str[End] == PunctuationEndStack.back())
467 PunctuationEndStack.pop_back();
468 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
469 PunctuationEndStack.push_back(SubEndPunct);
470
471 ++End;
472 }
473
474 // Find the first space character after the punctuation ended.
475 while (End < Length && !isspace(Str[End]))
476 ++End;
477
478 unsigned PunctWordLength = End - Start;
479 if (// If the word fits on this line
480 Column + PunctWordLength <= Columns ||
481 // ... or the word is "short enough" to take up the next line
482 // without too much ugly white space
483 PunctWordLength < Columns/3)
484 return End; // Take the whole thing as a single "word".
485
486 // The whole quoted/parenthesized string is too long to print as a
487 // single "word". Instead, find the "word" that starts just after
488 // the punctuation and use that end-point instead. This will recurse
489 // until it finds something small enough to consider a word.
490 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
491}
492
493/// \brief Print the given string to a stream, word-wrapping it to
494/// some number of columns in the process.
495///
496/// \brief OS the stream to which the word-wrapping string will be
497/// emitted.
498///
499/// \brief Str the string to word-wrap and output.
500///
501/// \brief Columns the number of columns to word-wrap to.
502///
503/// \brief Column the column number at which the first character of \p
504/// Str will be printed. This will be non-zero when part of the first
505/// line has already been printed.
506///
507/// \brief Indentation the number of spaces to indent any lines beyond
508/// the first line.
509///
510/// \returns true if word-wrapping was required, or false if the
511/// string fit on the first line.
512static bool PrintWordWrapped(llvm::raw_ostream &OS,
513 const llvm::SmallVectorImpl<char> &Str,
514 unsigned Columns,
515 unsigned Column = 0,
516 unsigned Indentation = WordWrapIndentation) {
517 unsigned Length = Str.size();
518
519 // If there is a newline in this message somewhere, find that
520 // newline and split the message into the part before the newline
521 // (which will be word-wrapped) and the part from the newline one
522 // (which will be emitted unchanged).
523 for (unsigned I = 0; I != Length; ++I)
524 if (Str[I] == '\n') {
525 Length = I;
526 break;
527 }
528
529 // The string used to indent each line.
530 llvm::SmallString<16> IndentStr;
531 IndentStr.assign(Indentation, ' ');
532 bool Wrapped = false;
533 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
534 WordStart = WordEnd) {
535 // Find the beginning of the next word.
536 WordStart = skipWhitespace(WordStart, Str, Length);
537 if (WordStart == Length)
538 break;
539
540 // Find the end of this word.
541 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
542
543 // Does this word fit on the current line?
544 unsigned WordLength = WordEnd - WordStart;
545 if (Column + WordLength < Columns) {
546 // This word fits on the current line; print it there.
547 if (WordStart) {
548 OS << ' ';
549 Column += 1;
550 }
551 OS.write(&Str[WordStart], WordLength);
552 Column += WordLength;
553 continue;
554 }
555
556 // This word does not fit on the current line, so wrap to the next
557 // line.
Douglas Gregor44cf08e2009-05-03 03:52:38 +0000558 OS << '\n';
559 OS.write(&IndentStr[0], Indentation);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000560 OS.write(&Str[WordStart], WordLength);
561 Column = Indentation + WordLength;
562 Wrapped = true;
563 }
564
565 if (Length == Str.size())
566 return Wrapped; // We're done.
567
568 // There is a newline in the message, followed by something that
569 // will not be word-wrapped. Print that.
570 OS.write(&Str[Length], Str.size() - Length);
571 return true;
572}
Chris Lattner94f55782009-02-17 07:38:37 +0000573
Chris Lattner0a14eee2008-11-18 07:04:44 +0000574void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
575 const DiagnosticInfo &Info) {
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000576 // Keeps track of the the starting position of the location
577 // information (e.g., "foo.c:10:4:") that precedes the error
578 // message. We use this information to determine how long the
579 // file+line+column number prefix is.
580 uint64_t StartOfLocationInfo = OS.tell();
581
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000582 // If the location is specified, print out a file/line/col and include trace
583 // if enabled.
584 if (Info.getLocation().isValid()) {
Ted Kremenek05f39572009-01-28 20:47:47 +0000585 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000586 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
587 unsigned LineNo = PLoc.getLine();
Reid Spencer5f016e22007-07-11 17:01:13 +0000588
589 // First, if this diagnostic is not in the main file, print out the
590 // "included from" lines.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000591 if (LastWarningLoc != PLoc.getIncludeLoc()) {
592 LastWarningLoc = PLoc.getIncludeLoc();
593 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000594 StartOfLocationInfo = OS.tell();
Reid Spencer5f016e22007-07-11 17:01:13 +0000595 }
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000596
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000597 // Compute the column number.
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000598 if (ShowLocation) {
599 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattner8f7b3962009-02-17 07:34:34 +0000600 if (ShowColumn)
601 if (unsigned ColNo = PLoc.getColumn())
602 OS << ColNo << ':';
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000603
604 if (PrintRangeInfo && Info.getNumRanges()) {
605 FileID CaretFileID =
606 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
607 bool PrintedRange = false;
608
609 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner74548e62009-04-19 22:24:10 +0000610 // Ignore invalid ranges.
611 if (!Info.getRange(i).isValid()) continue;
612
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000613 SourceLocation B = Info.getRange(i).getBegin();
614 SourceLocation E = Info.getRange(i).getEnd();
615 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
616
617 E = SM.getInstantiationLoc(E);
618 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
619
620 // If the start or end of the range is in another file, just discard
621 // it.
622 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
623 continue;
624
625 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattner2c78b872009-04-14 23:22:57 +0000626 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner1fbee5d2009-03-13 01:08:23 +0000627
628 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
629 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
630 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
631 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
632 PrintedRange = true;
633 }
634
635 if (PrintedRange)
636 OS << ':';
637 }
Chris Lattnerb8bf65e2009-01-30 17:41:53 +0000638 OS << ' ';
639 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
641
642 switch (Level) {
Chris Lattner41327582009-02-06 03:57:44 +0000643 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman165b9542008-04-17 18:06:57 +0000644 case Diagnostic::Note: OS << "note: "; break;
645 case Diagnostic::Warning: OS << "warning: "; break;
646 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner41327582009-02-06 03:57:44 +0000647 case Diagnostic::Fatal: OS << "fatal error: "; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 }
649
Chris Lattnerf4c83962008-11-19 06:51:40 +0000650 llvm::SmallString<100> OutStr;
651 Info.FormatDiagnostic(OutStr);
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000652
653 if (PrintDiagnosticOption)
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000654 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
655 OutStr += " [-W";
656 OutStr += Opt;
657 OutStr += ']';
658 }
Chris Lattnerd51d74a2009-04-16 05:44:38 +0000659
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000660 if (MessageLength) {
661 // We will be word-wrapping the error message, so compute the
662 // column number where we currently are (after printing the
663 // location information).
664 unsigned Column = OS.tell() - StartOfLocationInfo;
Douglas Gregor2cc2b9c2009-05-06 04:43:47 +0000665 PrintWordWrapped(OS, OutStr, MessageLength, Column);
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000666 } else {
667 OS.write(OutStr.begin(), OutStr.size());
668 }
Chris Lattnerf4c83962008-11-19 06:51:40 +0000669 OS << '\n';
Reid Spencer5f016e22007-07-11 17:01:13 +0000670
Douglas Gregordf667e72009-03-10 20:44:00 +0000671 // If caret diagnostics are enabled and we have location, we want to
672 // emit the caret. However, we only do this if the location moved
673 // from the last diagnostic, if the last diagnostic was a note that
674 // was part of a different warning or error diagnostic, or if the
675 // diagnostic has ranges. We don't want to emit the same caret
676 // multiple times if one loc has multiple diagnostics.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000677 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000678 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregordf667e72009-03-10 20:44:00 +0000679 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000680 Info.getNumCodeModificationHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +0000681 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000682 LastLoc = Info.getLocation();
Douglas Gregordf667e72009-03-10 20:44:00 +0000683 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000684
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000685 // Get the ranges into a local array we can hack on.
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000686 SourceRange Ranges[20];
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000687 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000688 assert(NumRanges < 20 && "Out of space");
Chris Lattnerebbbb1b2009-02-20 00:18:51 +0000689 for (unsigned i = 0; i != NumRanges; ++i)
690 Ranges[i] = Info.getRange(i);
691
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000692 unsigned NumHints = Info.getNumCodeModificationHints();
693 for (unsigned idx = 0; idx < NumHints; ++idx) {
694 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
695 if (Hint.RemoveRange.isValid()) {
696 assert(NumRanges < 20 && "Out of space");
697 Ranges[NumRanges++] = Hint.RemoveRange;
698 }
699 }
700
701 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
702 Info.getCodeModificationHints(),
Douglas Gregorfffd93f2009-05-01 21:53:04 +0000703 Info.getNumCodeModificationHints(),
Douglas Gregor47f71772009-05-01 23:32:58 +0000704 MessageLength);
Reid Spencer5f016e22007-07-11 17:01:13 +0000705 }
Chris Lattnera03a5b52008-11-19 06:56:25 +0000706
707 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +0000708}