blob: e8492ea0a8dd40570cc733afed56580ff4fde852 [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 Lattner92a33532008-11-19 06:56:25 +000017#include "llvm/Support/raw_ostream.h"
Chris Lattnerbe8e5a42008-11-19 06:51:40 +000018#include "llvm/ADT/SmallString.h"
Douglas Gregor3bb30002009-02-26 21:00:50 +000019#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000020using namespace clang;
21
Douglas Gregora4eb3e72009-05-01 21:53:04 +000022/// \brief Number of spaces to indent when word-wrapping.
23const unsigned WordWrapIndentation = 6;
24
Chris Lattner4b009652007-07-25 00:24:17 +000025void TextDiagnosticPrinter::
Chris Lattner836774b2009-01-27 07:57:44 +000026PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
27 if (Loc.isInvalid()) return;
Chris Lattner4b009652007-07-25 00:24:17 +000028
Chris Lattner836774b2009-01-27 07:57:44 +000029 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Chris Lattner4b009652007-07-25 00:24:17 +000030
31 // Print out the other include frames first.
Chris Lattner836774b2009-01-27 07:57:44 +000032 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
Chris Lattnerfd0739e2009-04-21 03:57:54 +000033
34 if (ShowLocation)
35 OS << "In file included from " << PLoc.getFilename()
36 << ':' << PLoc.getLine() << ":\n";
37 else
38 OS << "In included file:\n";
Chris Lattner4b009652007-07-25 00:24:17 +000039}
40
41/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
42/// any characters in LineNo that intersect the SourceRange.
Ted Kremenekb3ee1932007-12-11 21:27:55 +000043void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
Chris Lattner836774b2009-01-27 07:57:44 +000044 const SourceManager &SM,
Chris Lattner10aaf532009-01-17 08:45:21 +000045 unsigned LineNo, FileID FID,
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000046 std::string &CaretLine,
Nuno Lopesd0e162c2008-08-05 19:40:20 +000047 const std::string &SourceLine) {
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000048 assert(CaretLine.size() == SourceLine.size() &&
49 "Expect a correspondence between source and caret line!");
Chris Lattner4b009652007-07-25 00:24:17 +000050 if (!R.isValid()) return;
51
Chris Lattner836774b2009-01-27 07:57:44 +000052 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
53 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
54
Chris Lattnere357b112009-02-17 05:19:10 +000055 // If the End location and the start location are the same and are a macro
56 // location, then the range was something that came from a macro expansion
57 // or _Pragma. If this is an object-like macro, the best we can do is to
58 // highlight the range. If this is a function-like macro, we'd also like to
59 // highlight the arguments.
60 if (Begin == End && R.getEnd().isMacroID())
61 End = SM.getInstantiationRange(R.getEnd()).second;
62
Chris Lattner2d89c562009-02-04 01:06:56 +000063 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
Chris Lattner836774b2009-01-27 07:57:44 +000064 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
Chris Lattnera0030d22008-01-12 06:43:35 +000065 return; // No intersection.
Chris Lattner4b009652007-07-25 00:24:17 +000066
Chris Lattner2d89c562009-02-04 01:06:56 +000067 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
Chris Lattner836774b2009-01-27 07:57:44 +000068 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
Chris Lattnera0030d22008-01-12 06:43:35 +000069 return; // No intersection.
Chris Lattner4b009652007-07-25 00:24:17 +000070
71 // Compute the column number of the start.
72 unsigned StartColNo = 0;
73 if (StartLineNo == LineNo) {
Chris Lattnere79fc852009-02-04 00:55:58 +000074 StartColNo = SM.getInstantiationColumnNumber(Begin);
Chris Lattner4b009652007-07-25 00:24:17 +000075 if (StartColNo) --StartColNo; // Zero base the col #.
76 }
77
78 // Pick the first non-whitespace column.
79 while (StartColNo < SourceLine.size() &&
80 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
81 ++StartColNo;
82
83 // Compute the column number of the end.
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000084 unsigned EndColNo = CaretLine.size();
Chris Lattner4b009652007-07-25 00:24:17 +000085 if (EndLineNo == LineNo) {
Chris Lattnere79fc852009-02-04 00:55:58 +000086 EndColNo = SM.getInstantiationColumnNumber(End);
Chris Lattner4b009652007-07-25 00:24:17 +000087 if (EndColNo) {
88 --EndColNo; // Zero base the col #.
89
90 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +000091 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
Chris Lattner4b009652007-07-25 00:24:17 +000092 } else {
Gordon Henriksenf0a835c2008-08-09 19:58:22 +000093 EndColNo = CaretLine.size();
Chris Lattner4b009652007-07-25 00:24:17 +000094 }
95 }
96
97 // Pick the last non-whitespace column.
Nuno Lopesd0e162c2008-08-05 19:40:20 +000098 if (EndColNo <= SourceLine.size())
99 while (EndColNo-1 &&
100 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
101 --EndColNo;
102 else
103 EndColNo = SourceLine.size();
Chris Lattner4b009652007-07-25 00:24:17 +0000104
105 // Fill the range with ~'s.
106 assert(StartColNo <= EndColNo && "Invalid range!");
Nuno Lopesd0e162c2008-08-05 19:40:20 +0000107 for (unsigned i = StartColNo; i < EndColNo; ++i)
Gordon Henriksenf0a835c2008-08-09 19:58:22 +0000108 CaretLine[i] = '~';
Chris Lattner4b009652007-07-25 00:24:17 +0000109}
110
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000111/// \brief When the source code line we want to print is too long for
112/// the terminal, select the "interesting" region.
113static void SelectInterestingSourceRegion(std::string &SourceLine,
114 std::string &CaretLine,
115 std::string &FixItInsertionLine,
Douglas Gregor47629432009-05-04 06:27:32 +0000116 unsigned EndOfCaretToken,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000117 unsigned Columns) {
118 if (CaretLine.size() > SourceLine.size())
119 SourceLine.resize(CaretLine.size(), ' ');
120
121 // Find the slice that we need to display the full caret line
122 // correctly.
123 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
124 for (; CaretStart != CaretEnd; ++CaretStart)
125 if (!isspace(CaretLine[CaretStart]))
126 break;
127
128 for (; CaretEnd != CaretStart; --CaretEnd)
129 if (!isspace(CaretLine[CaretEnd - 1]))
130 break;
Douglas Gregor47629432009-05-04 06:27:32 +0000131
132 // Make sure we don't chop the string shorter than the caret token
133 // itself.
134 if (CaretEnd < EndOfCaretToken)
135 CaretEnd = EndOfCaretToken;
136
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000137 // If we have a fix-it line, make sure the slice includes all of the
138 // fix-it information.
139 if (!FixItInsertionLine.empty()) {
140 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
141 for (; FixItStart != FixItEnd; ++FixItStart)
142 if (!isspace(FixItInsertionLine[FixItStart]))
143 break;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000144
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000145 for (; FixItEnd != FixItStart; --FixItEnd)
146 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
147 break;
148
149 if (FixItStart < CaretStart)
150 CaretStart = FixItStart;
151 if (FixItEnd > CaretEnd)
152 CaretEnd = FixItEnd;
153 }
154
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000155 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
156 // parts of the caret line. While this slice is smaller than the
157 // number of columns we have, try to grow the slice to encompass
158 // more context.
159
160 // If the end of the interesting region comes before we run out of
161 // space in the terminal, start at the beginning of the line.
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000162 if (CaretEnd < Columns - 3)
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000163 CaretStart = 0;
164
Douglas Gregor99bb2922009-05-03 04:12:51 +0000165 unsigned TargetColumns = Columns - 8; // Give us extra room for the ellipses.
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000166 unsigned SourceLength = SourceLine.size();
Douglas Gregor394b6222009-05-04 06:45:38 +0000167 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000168 bool ExpandedRegion = false;
169 // Move the start of the interesting region left until we've
170 // pulled in something else interesting.
Douglas Gregor394b6222009-05-04 06:45:38 +0000171 if (CaretStart == 1)
172 CaretStart = 0;
173 else if (CaretStart > 1) {
174 unsigned NewStart = CaretStart - 1;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000175
Douglas Gregor394b6222009-05-04 06:45:38 +0000176 // Skip over any whitespace we see here; we're looking for
177 // another bit of interesting text.
178 while (NewStart && isspace(SourceLine[NewStart]))
179 --NewStart;
180
181 // Skip over this bit of "interesting" text.
182 while (NewStart && !isspace(SourceLine[NewStart]))
183 --NewStart;
184
185 // Move up to the non-whitespace character we just saw.
186 if (NewStart)
187 ++NewStart;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000188
189 // If we're still within our limit, update the starting
190 // position within the source/caret line.
Douglas Gregor394b6222009-05-04 06:45:38 +0000191 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000192 CaretStart = NewStart;
193 ExpandedRegion = true;
194 }
195 }
196
197 // Move the end of the interesting region right until we've
198 // pulled in something else interesting.
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000199 if (CaretEnd != SourceLength) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000200 unsigned NewEnd = CaretEnd;
201
202 // Skip over any whitespace we see here; we're looking for
203 // another bit of interesting text.
204 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
205 ++NewEnd;
206
207 // Skip over this bit of "interesting" text.
208 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
209 ++NewEnd;
210
211 if (NewEnd - CaretStart <= TargetColumns) {
212 CaretEnd = NewEnd;
213 ExpandedRegion = true;
214 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000215 }
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000216
217 if (!ExpandedRegion)
218 break;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000219 }
220
221 // [CaretStart, CaretEnd) is the slice we want. Update the various
222 // output lines to show only this slice, with two-space padding
223 // before the lines so that it looks nicer.
Douglas Gregor99bb2922009-05-03 04:12:51 +0000224 if (CaretEnd < SourceLine.size())
225 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000226 if (CaretEnd < CaretLine.size())
227 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000228 if (FixItInsertionLine.size() > CaretEnd)
229 FixItInsertionLine.erase(CaretEnd, std::string::npos);
230
231 if (CaretStart > 2) {
Douglas Gregor99bb2922009-05-03 04:12:51 +0000232 SourceLine.replace(0, CaretStart, " ...");
233 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000234 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor99bb2922009-05-03 04:12:51 +0000235 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000236 }
237}
238
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000239void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000240 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000241 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000242 SourceManager &SM,
243 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000244 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000245 unsigned AvoidColumn,
246 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000247 assert(!Loc.isInvalid() && "must have a valid source location here");
248
Chris Lattner3b29a182009-02-17 07:54:55 +0000249 // We always emit diagnostics about the instantiation points, not the spelling
250 // points. This more closely correlates to what the user writes.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000251 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000252 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000253 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
254 Columns);
Chris Lattner37f9ad22009-02-17 08:44:50 +0000255
Chris Lattner3272e922009-02-20 00:25:28 +0000256 // Map the location through the macro.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000257 Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
Chris Lattner3272e922009-02-20 00:25:28 +0000258
259 // Map the ranges.
260 for (unsigned i = 0; i != NumRanges; ++i) {
261 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
262 if (S.isMacroID())
263 S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
264 if (E.isMacroID())
265 E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
266 Ranges[i] = SourceRange(S, E);
267 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000268
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000269 if (ShowLocation) {
270 // Emit the file/line/column that this expansion came from.
271 OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
272 << ':';
273 if (ShowColumn)
274 OS << SM.getInstantiationColumnNumber(Loc) << ':';
275 OS << ' ';
276 }
277 OS << "note: instantiated from:\n";
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000278 AvoidColumn = 0;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000279 }
Chris Lattner34e6c262009-02-17 07:51:53 +0000280
281 // Decompose the location into a FID/Offset pair.
282 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
283 FileID FID = LocInfo.first;
284 unsigned FileOffset = LocInfo.second;
285
286 // Get information about the buffer it points into.
287 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
288 const char *BufStart = BufferInfo.first;
Chris Lattner34e6c262009-02-17 07:51:53 +0000289
290 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Douglas Gregor47629432009-05-04 06:27:32 +0000291 unsigned CaretEndColNo
292 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
293
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000294 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000295 const char *TokPtr = BufStart+FileOffset;
296 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
297
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000298
299 // Compute the line end. Scan forward from the error position to the end of
300 // the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000301 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000302 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000303 ++LineEnd;
304
305 // Copy the line of code into an std::string for ease of manipulation.
306 std::string SourceLine(LineStart, LineEnd);
307
308 // Create a line for the caret that is filled with spaces that is the same
309 // length as the line of source code.
310 std::string CaretLine(LineEnd-LineStart, ' ');
311
312 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000313 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000314 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
315
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000316 for (unsigned i = 0, e = NumRanges; i != e; ++i)
317 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattner34e6c262009-02-17 07:51:53 +0000318 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000319
320 // Next, insert the caret itself.
321 if (ColNo-1 < CaretLine.size())
322 CaretLine[ColNo-1] = '^';
323 else
324 CaretLine.push_back('^');
325
326 // Scan the source line, looking for tabs. If we find any, manually expand
327 // them to 8 characters and update the CaretLine to match.
328 for (unsigned i = 0; i != SourceLine.size(); ++i) {
329 if (SourceLine[i] != '\t') continue;
330
331 // Replace this tab with at least one space.
332 SourceLine[i] = ' ';
333
334 // Compute the number of spaces we need to insert.
335 unsigned NumSpaces = ((i+8)&~7) - (i+1);
336 assert(NumSpaces < 8 && "Invalid computation of space amt");
337
338 // Insert spaces into the SourceLine.
339 SourceLine.insert(i+1, NumSpaces, ' ');
340
341 // Insert spaces or ~'s into CaretLine.
342 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
343 }
344
Chris Lattner404ba8e2009-04-28 22:33:16 +0000345 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
346 // produce easily machine parsable output. Add a space before the source line
347 // and the caret to make it trivial to tell the main diagnostic line from what
348 // the user is intended to see.
349 if (PrintRangeInfo) {
350 SourceLine = ' ' + SourceLine;
351 CaretLine = ' ' + CaretLine;
352 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000353
354 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000355 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000356 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000357 Hint != LastHint; ++Hint) {
358 if (Hint->InsertionLoc.isValid()) {
359 // We have an insertion hint. Determine whether the inserted
360 // code is on the same line as the caret.
361 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner9ccffa72009-03-02 20:58:48 +0000362 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000363 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
364 SM.getLineNumber(FID, FileOffset)) {
365 // Insert the new code into the line just below the code
366 // that the user wrote.
367 unsigned HintColNo
368 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
369 unsigned LastColumnModified
370 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000371 if (LastColumnModified > FixItInsertionLine.size())
372 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000373 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000374 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000375 } else {
376 FixItInsertionLine.clear();
377 break;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000378 }
379 }
380 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000381 }
Douglas Gregor3bb30002009-02-26 21:00:50 +0000382
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000383 // If the source line is too long for our terminal, select only the
384 // "interesting" source region within that line.
385 if (Columns && SourceLine.size() > Columns)
386 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Douglas Gregor47629432009-05-04 06:27:32 +0000387 CaretEndColNo, Columns);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000388
389 // AvoidColumn tells us which column we should avoid when printing
390 // the source line. If the source line would start at or near that
391 // column, add another line of whitespace before printing the source
392 // line. Otherwise, the source line and the diagnostic text can get
393 // jumbled together.
394 unsigned StartCol = 0;
395 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
396 if (!isspace(SourceLine[StartCol]))
397 break;
398
399 if (StartCol != SourceLine.size() &&
400 abs((int)StartCol - (int)AvoidColumn) <= 2)
401 OS << '\n';
402
403 // Finally, remove any blank spaces from the end of CaretLine.
404 while (CaretLine[CaretLine.size()-1] == ' ')
405 CaretLine.erase(CaretLine.end()-1);
406
407 // Emit what we have computed.
408 OS << SourceLine << '\n';
409 OS << CaretLine << '\n';
410
411 if (!FixItInsertionLine.empty()) {
412 if (PrintRangeInfo)
413 OS << ' ';
414 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000415 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000416}
417
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000418/// \brief Skip over whitespace in the string, starting at the given
419/// index.
420///
421/// \returns The index of the first non-whitespace character that is
422/// greater than or equal to Idx or, if no such character exists,
423/// returns the end of the string.
424static unsigned skipWhitespace(unsigned Idx,
425 const llvm::SmallVectorImpl<char> &Str,
426 unsigned Length) {
427 while (Idx < Length && isspace(Str[Idx]))
428 ++Idx;
429 return Idx;
430}
431
432/// \brief If the given character is the start of some kind of
433/// balanced punctuation (e.g., quotes or parentheses), return the
434/// character that will terminate the punctuation.
435///
436/// \returns The ending punctuation character, if any, or the NULL
437/// character if the input character does not start any punctuation.
438static inline char findMatchingPunctuation(char c) {
439 switch (c) {
440 case '\'': return '\'';
441 case '`': return '\'';
442 case '"': return '"';
443 case '(': return ')';
444 case '[': return ']';
445 case '{': return '}';
446 default: break;
447 }
448
449 return 0;
450}
451
452/// \brief Find the end of the word starting at the given offset
453/// within a string.
454///
455/// \returns the index pointing one character past the end of the
456/// word.
457unsigned findEndOfWord(unsigned Start,
458 const llvm::SmallVectorImpl<char> &Str,
459 unsigned Length, unsigned Column,
460 unsigned Columns) {
461 unsigned End = Start + 1;
462
463 // Determine if the start of the string is actually opening
464 // punctuation, e.g., a quote or parentheses.
465 char EndPunct = findMatchingPunctuation(Str[Start]);
466 if (!EndPunct) {
467 // This is a normal word. Just find the first space character.
468 while (End < Length && !isspace(Str[End]))
469 ++End;
470 return End;
471 }
472
473 // We have the start of a balanced punctuation sequence (quotes,
474 // parentheses, etc.). Determine the full sequence is.
475 llvm::SmallVector<char, 16> PunctuationEndStack;
476 PunctuationEndStack.push_back(EndPunct);
477 while (End < Length && !PunctuationEndStack.empty()) {
478 if (Str[End] == PunctuationEndStack.back())
479 PunctuationEndStack.pop_back();
480 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
481 PunctuationEndStack.push_back(SubEndPunct);
482
483 ++End;
484 }
485
486 // Find the first space character after the punctuation ended.
487 while (End < Length && !isspace(Str[End]))
488 ++End;
489
490 unsigned PunctWordLength = End - Start;
491 if (// If the word fits on this line
492 Column + PunctWordLength <= Columns ||
493 // ... or the word is "short enough" to take up the next line
494 // without too much ugly white space
495 PunctWordLength < Columns/3)
496 return End; // Take the whole thing as a single "word".
497
498 // The whole quoted/parenthesized string is too long to print as a
499 // single "word". Instead, find the "word" that starts just after
500 // the punctuation and use that end-point instead. This will recurse
501 // until it finds something small enough to consider a word.
502 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
503}
504
505/// \brief Print the given string to a stream, word-wrapping it to
506/// some number of columns in the process.
507///
508/// \brief OS the stream to which the word-wrapping string will be
509/// emitted.
510///
511/// \brief Str the string to word-wrap and output.
512///
513/// \brief Columns the number of columns to word-wrap to.
514///
515/// \brief Column the column number at which the first character of \p
516/// Str will be printed. This will be non-zero when part of the first
517/// line has already been printed.
518///
519/// \brief Indentation the number of spaces to indent any lines beyond
520/// the first line.
521///
522/// \returns true if word-wrapping was required, or false if the
523/// string fit on the first line.
524static bool PrintWordWrapped(llvm::raw_ostream &OS,
525 const llvm::SmallVectorImpl<char> &Str,
526 unsigned Columns,
527 unsigned Column = 0,
528 unsigned Indentation = WordWrapIndentation) {
529 unsigned Length = Str.size();
530
531 // If there is a newline in this message somewhere, find that
532 // newline and split the message into the part before the newline
533 // (which will be word-wrapped) and the part from the newline one
534 // (which will be emitted unchanged).
535 for (unsigned I = 0; I != Length; ++I)
536 if (Str[I] == '\n') {
537 Length = I;
538 break;
539 }
540
541 // The string used to indent each line.
542 llvm::SmallString<16> IndentStr;
543 IndentStr.assign(Indentation, ' ');
544 bool Wrapped = false;
545 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
546 WordStart = WordEnd) {
547 // Find the beginning of the next word.
548 WordStart = skipWhitespace(WordStart, Str, Length);
549 if (WordStart == Length)
550 break;
551
552 // Find the end of this word.
553 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
554
555 // Does this word fit on the current line?
556 unsigned WordLength = WordEnd - WordStart;
557 if (Column + WordLength < Columns) {
558 // This word fits on the current line; print it there.
559 if (WordStart) {
560 OS << ' ';
561 Column += 1;
562 }
563 OS.write(&Str[WordStart], WordLength);
564 Column += WordLength;
565 continue;
566 }
567
568 // This word does not fit on the current line, so wrap to the next
569 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000570 OS << '\n';
571 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000572 OS.write(&Str[WordStart], WordLength);
573 Column = Indentation + WordLength;
574 Wrapped = true;
575 }
576
577 if (Length == Str.size())
578 return Wrapped; // We're done.
579
580 // There is a newline in the message, followed by something that
581 // will not be word-wrapped. Print that.
582 OS.write(&Str[Length], Str.size() - Length);
583 return true;
584}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000585
Chris Lattner6948ae62008-11-18 07:04:44 +0000586void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
587 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000588 // Keeps track of the the starting position of the location
589 // information (e.g., "foo.c:10:4:") that precedes the error
590 // message. We use this information to determine how long the
591 // file+line+column number prefix is.
592 uint64_t StartOfLocationInfo = OS.tell();
593
Chris Lattner836774b2009-01-27 07:57:44 +0000594 // If the location is specified, print out a file/line/col and include trace
595 // if enabled.
596 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000597 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000598 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
599 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000600
601 // First, if this diagnostic is not in the main file, print out the
602 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000603 if (LastWarningLoc != PLoc.getIncludeLoc()) {
604 LastWarningLoc = PLoc.getIncludeLoc();
605 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000606 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000607 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000608
Chris Lattner836774b2009-01-27 07:57:44 +0000609 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000610 if (ShowLocation) {
611 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000612 if (ShowColumn)
613 if (unsigned ColNo = PLoc.getColumn())
614 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000615
616 if (PrintRangeInfo && Info.getNumRanges()) {
617 FileID CaretFileID =
618 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
619 bool PrintedRange = false;
620
621 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000622 // Ignore invalid ranges.
623 if (!Info.getRange(i).isValid()) continue;
624
Chris Lattner695a4f52009-03-13 01:08:23 +0000625 SourceLocation B = Info.getRange(i).getBegin();
626 SourceLocation E = Info.getRange(i).getEnd();
627 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
628
629 E = SM.getInstantiationLoc(E);
630 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
631
632 // If the start or end of the range is in another file, just discard
633 // it.
634 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
635 continue;
636
637 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000638 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000639
640 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
641 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
642 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
643 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
644 PrintedRange = true;
645 }
646
647 if (PrintedRange)
648 OS << ':';
649 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000650 OS << ' ';
651 }
Chris Lattner4b009652007-07-25 00:24:17 +0000652 }
653
654 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000655 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000656 case Diagnostic::Note: OS << "note: "; break;
657 case Diagnostic::Warning: OS << "warning: "; break;
658 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000659 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000660 }
661
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000662 llvm::SmallString<100> OutStr;
663 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000664
665 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000666 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
667 OutStr += " [-W";
668 OutStr += Opt;
669 OutStr += ']';
670 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000671
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000672 bool WordWrapped = false;
673 if (MessageLength) {
674 // We will be word-wrapping the error message, so compute the
675 // column number where we currently are (after printing the
676 // location information).
677 unsigned Column = OS.tell() - StartOfLocationInfo;
678 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
679 } else {
680 OS.write(OutStr.begin(), OutStr.size());
681 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000682 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000683
Douglas Gregor56d25a72009-03-10 20:44:00 +0000684 // If caret diagnostics are enabled and we have location, we want to
685 // emit the caret. However, we only do this if the location moved
686 // from the last diagnostic, if the last diagnostic was a note that
687 // was part of a different warning or error diagnostic, or if the
688 // diagnostic has ranges. We don't want to emit the same caret
689 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000690 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000691 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000692 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000693 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000694 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000695 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000696 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000697
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000698 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000699 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000700 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000701 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000702 for (unsigned i = 0; i != NumRanges; ++i)
703 Ranges[i] = Info.getRange(i);
704
Douglas Gregor3bb30002009-02-26 21:00:50 +0000705 unsigned NumHints = Info.getNumCodeModificationHints();
706 for (unsigned idx = 0; idx < NumHints; ++idx) {
707 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
708 if (Hint.RemoveRange.isValid()) {
709 assert(NumRanges < 20 && "Out of space");
710 Ranges[NumRanges++] = Hint.RemoveRange;
711 }
712 }
713
714 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
715 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000716 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000717 WordWrapped? WordWrapIndentation : 0,
718 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000719 }
Chris Lattner92a33532008-11-19 06:56:25 +0000720
721 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000722}