blob: 09c29109f18f1edc2f33850a2bec42f3fa756564 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar68952de2009-03-02 06:16:29 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#include "clang/Lex/Lexer.h"
Chris Lattner3669cca2009-05-05 22:03:18 +000017#include "llvm/Support/MemoryBuffer.h"
Chris Lattner92a33532008-11-19 06:56:25 +000018#include "llvm/Support/raw_ostream.h"
Chris Lattnerbe8e5a42008-11-19 06:51:40 +000019#include "llvm/ADT/SmallString.h"
Douglas Gregor3bb30002009-02-26 21:00:50 +000020#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22
Douglas Gregora4eb3e72009-05-01 21:53:04 +000023/// \brief Number of spaces to indent when word-wrapping.
24const unsigned WordWrapIndentation = 6;
25
Chris Lattner4b009652007-07-25 00:24:17 +000026void TextDiagnosticPrinter::
Chris Lattner836774b2009-01-27 07:57:44 +000027PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
28 if (Loc.isInvalid()) return;
Chris Lattner4b009652007-07-25 00:24:17 +000029
Chris Lattner836774b2009-01-27 07:57:44 +000030 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner4b009652007-07-25 00:24:17 +000031
32 // Print out the other include frames first.
Chris Lattner836774b2009-01-27 07:57:44 +000033 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattnerfd0739e2009-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";
Chris Lattner4b009652007-07-25 00:24:17 +000040}
41
42/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
43/// any characters in LineNo that intersect the SourceRange.
Ted Kremenekb3ee1932007-12-11 21:27:55 +000044void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattner836774b2009-01-27 07:57:44 +000045 const SourceManager &SM,
Chris Lattner10aaf532009-01-17 08:45:21 +000046 unsigned LineNo, FileID FID,
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000047 std::string &CaretLine,
Nuno Lopesd0e162c2008-08-05 19:40:20 +000048 const std::string &SourceLine) {
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000049 assert(CaretLine.size() == SourceLine.size() &&
50 "Expect a correspondence between source and caret line!");
Chris Lattner4b009652007-07-25 00:24:17 +000051 if (!R.isValid()) return;
52
Chris Lattner836774b2009-01-27 07:57:44 +000053 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
54 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
55
Chris Lattnere357b112009-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 Lattner2d89c562009-02-04 01:06:56 +000064 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattner836774b2009-01-27 07:57:44 +000065 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnera0030d22008-01-12 06:43:35 +000066 return; // No intersection.
Chris Lattner4b009652007-07-25 00:24:17 +000067
Chris Lattner2d89c562009-02-04 01:06:56 +000068 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattner836774b2009-01-27 07:57:44 +000069 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnera0030d22008-01-12 06:43:35 +000070 return; // No intersection.
Chris Lattner4b009652007-07-25 00:24:17 +000071
72 // Compute the column number of the start.
73 unsigned StartColNo = 0;
74 if (StartLineNo == LineNo) {
Chris Lattnere79fc852009-02-04 00:55:58 +000075 StartColNo = SM.getInstantiationColumnNumber(Begin);
Chris Lattner4b009652007-07-25 00:24:17 +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 Henriksenf0a835c2008-08-09 19:58:22 +000085 unsigned EndColNo = CaretLine.size();
Chris Lattner4b009652007-07-25 00:24:17 +000086 if (EndLineNo == LineNo) {
Chris Lattnere79fc852009-02-04 00:55:58 +000087 EndColNo = SM.getInstantiationColumnNumber(End);
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnere1be6022009-04-14 23:22:57 +000092 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Chris Lattner4b009652007-07-25 00:24:17 +000093 } else {
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000094 EndColNo = CaretLine.size();
Chris Lattner4b009652007-07-25 00:24:17 +000095 }
96 }
97
98 // Pick the last non-whitespace column.
Nuno Lopesd0e162c2008-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();
Chris Lattner4b009652007-07-25 00:24:17 +0000105
106 // Fill the range with ~'s.
107 assert(StartColNo <= EndColNo && "Invalid range!");
Nuno Lopesd0e162c2008-08-05 19:40:20 +0000108 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenf0a835c2008-08-09 19:58:22 +0000109 CaretLine[i] = '~';
Chris Lattner4b009652007-07-25 00:24:17 +0000110}
111
Douglas Gregorf2ab4fb2009-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 Gregor47629432009-05-04 06:27:32 +0000117 unsigned EndOfCaretToken,
Douglas Gregorf2ab4fb2009-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 Gregor47629432009-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 Gregorb5579aa2009-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 Gregorf2ab4fb2009-05-01 23:32:58 +0000145
Douglas Gregorb5579aa2009-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 Gregorf2ab4fb2009-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 Gregorf1d5a342009-05-15 18:05:24 +0000163 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000164 CaretStart = 0;
165
Douglas Gregorf1d5a342009-05-15 18:05:24 +0000166 unsigned TargetColumns = Columns;
167 if (TargetColumns > 8)
168 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000169 unsigned SourceLength = SourceLine.size();
Douglas Gregor394b6222009-05-04 06:45:38 +0000170 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000171 bool ExpandedRegion = false;
172 // Move the start of the interesting region left until we've
173 // pulled in something else interesting.
Douglas Gregor394b6222009-05-04 06:45:38 +0000174 if (CaretStart == 1)
175 CaretStart = 0;
176 else if (CaretStart > 1) {
177 unsigned NewStart = CaretStart - 1;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000178
Douglas Gregor394b6222009-05-04 06:45:38 +0000179 // Skip over any whitespace we see here; we're looking for
180 // another bit of interesting text.
181 while (NewStart && isspace(SourceLine[NewStart]))
182 --NewStart;
183
184 // Skip over this bit of "interesting" text.
185 while (NewStart && !isspace(SourceLine[NewStart]))
186 --NewStart;
187
188 // Move up to the non-whitespace character we just saw.
189 if (NewStart)
190 ++NewStart;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000191
192 // If we're still within our limit, update the starting
193 // position within the source/caret line.
Douglas Gregor394b6222009-05-04 06:45:38 +0000194 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000195 CaretStart = NewStart;
196 ExpandedRegion = true;
197 }
198 }
199
200 // Move the end of the interesting region right until we've
201 // pulled in something else interesting.
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000202 if (CaretEnd != SourceLength) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000203 unsigned NewEnd = CaretEnd;
204
205 // Skip over any whitespace we see here; we're looking for
206 // another bit of interesting text.
207 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
208 ++NewEnd;
209
210 // Skip over this bit of "interesting" text.
211 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
212 ++NewEnd;
213
214 if (NewEnd - CaretStart <= TargetColumns) {
215 CaretEnd = NewEnd;
216 ExpandedRegion = true;
217 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000218 }
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000219
220 if (!ExpandedRegion)
221 break;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000222 }
223
224 // [CaretStart, CaretEnd) is the slice we want. Update the various
225 // output lines to show only this slice, with two-space padding
226 // before the lines so that it looks nicer.
Douglas Gregor99bb2922009-05-03 04:12:51 +0000227 if (CaretEnd < SourceLine.size())
228 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000229 if (CaretEnd < CaretLine.size())
230 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000231 if (FixItInsertionLine.size() > CaretEnd)
232 FixItInsertionLine.erase(CaretEnd, std::string::npos);
233
234 if (CaretStart > 2) {
Douglas Gregor99bb2922009-05-03 04:12:51 +0000235 SourceLine.replace(0, CaretStart, " ...");
236 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000237 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor99bb2922009-05-03 04:12:51 +0000238 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000239 }
240}
241
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000242void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000243 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000244 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000245 SourceManager &SM,
246 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000247 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000248 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000249 assert(!Loc.isInvalid() && "must have a valid source location here");
Chris Lattner3669cca2009-05-05 22:03:18 +0000250
251 // If this is a macro ID, first emit information about where this was
252 // instantiated (recursively) then emit information about where. the token was
253 // spelled from.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000254 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000255 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Chris Lattner3669cca2009-05-05 22:03:18 +0000256 // FIXME: Map ranges?
Douglas Gregor0c0b4362009-05-06 04:43:47 +0000257 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns);
Chris Lattner3272e922009-02-20 00:25:28 +0000258
Chris Lattner3669cca2009-05-05 22:03:18 +0000259 Loc = SM.getImmediateSpellingLoc(Loc);
260
Chris Lattner3272e922009-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 Lattner3669cca2009-05-05 22:03:18 +0000264 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
265 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
Chris Lattner3272e922009-02-20 00:25:28 +0000266 Ranges[i] = SourceRange(S, E);
267 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000268
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000269 if (ShowLocation) {
Chris Lattner3669cca2009-05-05 22:03:18 +0000270 std::pair<FileID, unsigned> IInfo = SM.getDecomposedInstantiationLoc(Loc);
271
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000272 // Emit the file/line/column that this expansion came from.
Chris Lattner3669cca2009-05-05 22:03:18 +0000273 OS << SM.getBuffer(IInfo.first)->getBufferIdentifier() << ':'
274 << SM.getLineNumber(IInfo.first, IInfo.second) << ':';
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000275 if (ShowColumn)
Chris Lattner3669cca2009-05-05 22:03:18 +0000276 OS << SM.getColumnNumber(IInfo.first, IInfo.second) << ':';
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000277 OS << ' ';
278 }
279 OS << "note: instantiated from:\n";
Chris Lattner3669cca2009-05-05 22:03:18 +0000280
Douglas Gregor0c0b4362009-05-06 04:43:47 +0000281 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns);
Chris Lattner3669cca2009-05-05 22:03:18 +0000282 return;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000283 }
Chris Lattner34e6c262009-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 Lattner34e6c262009-02-17 07:51:53 +0000293
294 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Douglas Gregor47629432009-05-04 06:27:32 +0000295 unsigned CaretEndColNo
296 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
297
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000298 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000299 const char *TokPtr = BufStart+FileOffset;
300 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
301
Chris Lattnerc1303fb2009-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 Lattner34e6c262009-02-17 07:51:53 +0000305 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000306 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-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 Lattnerec52b7d2009-02-20 00:18:51 +0000317 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000318 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
319
Chris Lattnerec52b7d2009-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 Lattner34e6c262009-02-17 07:51:53 +0000322 }
Chris Lattnerc1303fb2009-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 Lattner404ba8e2009-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 Gregorf2ab4fb2009-05-01 23:32:58 +0000357
358 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000359 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000360 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-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 Lattner9ccffa72009-03-02 20:58:48 +0000366 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-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 Gregorf2ab4fb2009-05-01 23:32:58 +0000375 if (LastColumnModified > FixItInsertionLine.size())
376 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000377 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000378 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000379 } else {
380 FixItInsertionLine.clear();
381 break;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000382 }
383 }
384 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000385 }
Douglas Gregor3bb30002009-02-26 21:00:50 +0000386
Douglas Gregorf2ab4fb2009-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 Gregor47629432009-05-04 06:27:32 +0000391 CaretEndColNo, Columns);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000392
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000393 // Finally, remove any blank spaces from the end of CaretLine.
394 while (CaretLine[CaretLine.size()-1] == ' ')
395 CaretLine.erase(CaretLine.end()-1);
396
397 // Emit what we have computed.
398 OS << SourceLine << '\n';
399 OS << CaretLine << '\n';
400
401 if (!FixItInsertionLine.empty()) {
402 if (PrintRangeInfo)
403 OS << ' ';
404 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000405 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000406}
407
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000408/// \brief Skip over whitespace in the string, starting at the given
409/// index.
410///
411/// \returns The index of the first non-whitespace character that is
412/// greater than or equal to Idx or, if no such character exists,
413/// returns the end of the string.
414static unsigned skipWhitespace(unsigned Idx,
415 const llvm::SmallVectorImpl<char> &Str,
416 unsigned Length) {
417 while (Idx < Length && isspace(Str[Idx]))
418 ++Idx;
419 return Idx;
420}
421
422/// \brief If the given character is the start of some kind of
423/// balanced punctuation (e.g., quotes or parentheses), return the
424/// character that will terminate the punctuation.
425///
426/// \returns The ending punctuation character, if any, or the NULL
427/// character if the input character does not start any punctuation.
428static inline char findMatchingPunctuation(char c) {
429 switch (c) {
430 case '\'': return '\'';
431 case '`': return '\'';
432 case '"': return '"';
433 case '(': return ')';
434 case '[': return ']';
435 case '{': return '}';
436 default: break;
437 }
438
439 return 0;
440}
441
442/// \brief Find the end of the word starting at the given offset
443/// within a string.
444///
445/// \returns the index pointing one character past the end of the
446/// word.
447unsigned findEndOfWord(unsigned Start,
448 const llvm::SmallVectorImpl<char> &Str,
449 unsigned Length, unsigned Column,
450 unsigned Columns) {
451 unsigned End = Start + 1;
452
453 // Determine if the start of the string is actually opening
454 // punctuation, e.g., a quote or parentheses.
455 char EndPunct = findMatchingPunctuation(Str[Start]);
456 if (!EndPunct) {
457 // This is a normal word. Just find the first space character.
458 while (End < Length && !isspace(Str[End]))
459 ++End;
460 return End;
461 }
462
463 // We have the start of a balanced punctuation sequence (quotes,
464 // parentheses, etc.). Determine the full sequence is.
465 llvm::SmallVector<char, 16> PunctuationEndStack;
466 PunctuationEndStack.push_back(EndPunct);
467 while (End < Length && !PunctuationEndStack.empty()) {
468 if (Str[End] == PunctuationEndStack.back())
469 PunctuationEndStack.pop_back();
470 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
471 PunctuationEndStack.push_back(SubEndPunct);
472
473 ++End;
474 }
475
476 // Find the first space character after the punctuation ended.
477 while (End < Length && !isspace(Str[End]))
478 ++End;
479
480 unsigned PunctWordLength = End - Start;
481 if (// If the word fits on this line
482 Column + PunctWordLength <= Columns ||
483 // ... or the word is "short enough" to take up the next line
484 // without too much ugly white space
485 PunctWordLength < Columns/3)
486 return End; // Take the whole thing as a single "word".
487
488 // The whole quoted/parenthesized string is too long to print as a
489 // single "word". Instead, find the "word" that starts just after
490 // the punctuation and use that end-point instead. This will recurse
491 // until it finds something small enough to consider a word.
492 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
493}
494
495/// \brief Print the given string to a stream, word-wrapping it to
496/// some number of columns in the process.
497///
498/// \brief OS the stream to which the word-wrapping string will be
499/// emitted.
500///
501/// \brief Str the string to word-wrap and output.
502///
503/// \brief Columns the number of columns to word-wrap to.
504///
505/// \brief Column the column number at which the first character of \p
506/// Str will be printed. This will be non-zero when part of the first
507/// line has already been printed.
508///
509/// \brief Indentation the number of spaces to indent any lines beyond
510/// the first line.
511///
512/// \returns true if word-wrapping was required, or false if the
513/// string fit on the first line.
514static bool PrintWordWrapped(llvm::raw_ostream &OS,
515 const llvm::SmallVectorImpl<char> &Str,
516 unsigned Columns,
517 unsigned Column = 0,
518 unsigned Indentation = WordWrapIndentation) {
519 unsigned Length = Str.size();
520
521 // If there is a newline in this message somewhere, find that
522 // newline and split the message into the part before the newline
523 // (which will be word-wrapped) and the part from the newline one
524 // (which will be emitted unchanged).
525 for (unsigned I = 0; I != Length; ++I)
526 if (Str[I] == '\n') {
527 Length = I;
528 break;
529 }
530
531 // The string used to indent each line.
532 llvm::SmallString<16> IndentStr;
533 IndentStr.assign(Indentation, ' ');
534 bool Wrapped = false;
535 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
536 WordStart = WordEnd) {
537 // Find the beginning of the next word.
538 WordStart = skipWhitespace(WordStart, Str, Length);
539 if (WordStart == Length)
540 break;
541
542 // Find the end of this word.
543 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
544
545 // Does this word fit on the current line?
546 unsigned WordLength = WordEnd - WordStart;
547 if (Column + WordLength < Columns) {
548 // This word fits on the current line; print it there.
549 if (WordStart) {
550 OS << ' ';
551 Column += 1;
552 }
553 OS.write(&Str[WordStart], WordLength);
554 Column += WordLength;
555 continue;
556 }
557
558 // This word does not fit on the current line, so wrap to the next
559 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000560 OS << '\n';
561 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000562 OS.write(&Str[WordStart], WordLength);
563 Column = Indentation + WordLength;
564 Wrapped = true;
565 }
566
567 if (Length == Str.size())
568 return Wrapped; // We're done.
569
570 // There is a newline in the message, followed by something that
571 // will not be word-wrapped. Print that.
572 OS.write(&Str[Length], Str.size() - Length);
573 return true;
574}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000575
Chris Lattner6948ae62008-11-18 07:04:44 +0000576void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
577 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000578 // Keeps track of the the starting position of the location
579 // information (e.g., "foo.c:10:4:") that precedes the error
580 // message. We use this information to determine how long the
581 // file+line+column number prefix is.
582 uint64_t StartOfLocationInfo = OS.tell();
583
Chris Lattner836774b2009-01-27 07:57:44 +0000584 // If the location is specified, print out a file/line/col and include trace
585 // if enabled.
586 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000587 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000588 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
589 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000590
591 // First, if this diagnostic is not in the main file, print out the
592 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000593 if (LastWarningLoc != PLoc.getIncludeLoc()) {
594 LastWarningLoc = PLoc.getIncludeLoc();
595 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000596 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000597 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000598
Chris Lattner836774b2009-01-27 07:57:44 +0000599 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000600 if (ShowLocation) {
601 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000602 if (ShowColumn)
603 if (unsigned ColNo = PLoc.getColumn())
604 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000605
606 if (PrintRangeInfo && Info.getNumRanges()) {
607 FileID CaretFileID =
608 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
609 bool PrintedRange = false;
610
611 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000612 // Ignore invalid ranges.
613 if (!Info.getRange(i).isValid()) continue;
614
Chris Lattner695a4f52009-03-13 01:08:23 +0000615 SourceLocation B = Info.getRange(i).getBegin();
616 SourceLocation E = Info.getRange(i).getEnd();
617 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
618
619 E = SM.getInstantiationLoc(E);
620 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
621
622 // If the start or end of the range is in another file, just discard
623 // it.
624 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
625 continue;
626
627 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000628 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000629
630 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
631 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
632 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
633 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
634 PrintedRange = true;
635 }
636
637 if (PrintedRange)
638 OS << ':';
639 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000640 OS << ' ';
641 }
Chris Lattner4b009652007-07-25 00:24:17 +0000642 }
643
644 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000645 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000646 case Diagnostic::Note: OS << "note: "; break;
647 case Diagnostic::Warning: OS << "warning: "; break;
648 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000649 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
651
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000652 llvm::SmallString<100> OutStr;
653 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000654
655 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000656 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
657 OutStr += " [-W";
658 OutStr += Opt;
659 OutStr += ']';
660 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000661
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000662 if (MessageLength) {
663 // We will be word-wrapping the error message, so compute the
664 // column number where we currently are (after printing the
665 // location information).
666 unsigned Column = OS.tell() - StartOfLocationInfo;
Douglas Gregor0c0b4362009-05-06 04:43:47 +0000667 PrintWordWrapped(OS, OutStr, MessageLength, Column);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000668 } else {
669 OS.write(OutStr.begin(), OutStr.size());
670 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000671 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000672
Douglas Gregor56d25a72009-03-10 20:44:00 +0000673 // If caret diagnostics are enabled and we have location, we want to
674 // emit the caret. However, we only do this if the location moved
675 // from the last diagnostic, if the last diagnostic was a note that
676 // was part of a different warning or error diagnostic, or if the
677 // diagnostic has ranges. We don't want to emit the same caret
678 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000679 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000680 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000681 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000682 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000683 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000684 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000685 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000686
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000687 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000688 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000689 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000690 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000691 for (unsigned i = 0; i != NumRanges; ++i)
692 Ranges[i] = Info.getRange(i);
693
Douglas Gregor3bb30002009-02-26 21:00:50 +0000694 unsigned NumHints = Info.getNumCodeModificationHints();
695 for (unsigned idx = 0; idx < NumHints; ++idx) {
696 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
697 if (Hint.RemoveRange.isValid()) {
698 assert(NumRanges < 20 && "Out of space");
699 Ranges[NumRanges++] = Hint.RemoveRange;
700 }
701 }
702
703 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
704 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000705 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000706 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000707 }
Chris Lattner92a33532008-11-19 06:56:25 +0000708
709 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000710}