blob: 62446f33007945dd88333a0bda852829efaa0b67 [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 Whether this is a closing delimiter such as ')' or ']'.
112static inline bool isClosingDelimiter(char c) {
113 return c == ')' || c == ']' || c == '}';
114}
115
116/// \brief When the source code line we want to print is too long for
117/// the terminal, select the "interesting" region.
118static void SelectInterestingSourceRegion(std::string &SourceLine,
119 std::string &CaretLine,
120 std::string &FixItInsertionLine,
121 unsigned Columns) {
122 if (CaretLine.size() > SourceLine.size())
123 SourceLine.resize(CaretLine.size(), ' ');
124
125 // Find the slice that we need to display the full caret line
126 // correctly.
127 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
128 for (; CaretStart != CaretEnd; ++CaretStart)
129 if (!isspace(CaretLine[CaretStart]))
130 break;
131
132 for (; CaretEnd != CaretStart; --CaretEnd)
133 if (!isspace(CaretLine[CaretEnd - 1]))
134 break;
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000135
136 // If we have a fix-it line, make sure the slice includes all of the
137 // fix-it information.
138 if (!FixItInsertionLine.empty()) {
139 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
140 for (; FixItStart != FixItEnd; ++FixItStart)
141 if (!isspace(FixItInsertionLine[FixItStart]))
142 break;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000143
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000144 for (; FixItEnd != FixItStart; --FixItEnd)
145 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
146 break;
147
148 if (FixItStart < CaretStart)
149 CaretStart = FixItStart;
150 if (FixItEnd > CaretEnd)
151 CaretEnd = FixItEnd;
152 }
153
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000154 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
155 // parts of the caret line. While this slice is smaller than the
156 // number of columns we have, try to grow the slice to encompass
157 // more context.
158
159 // If the end of the interesting region comes before we run out of
160 // space in the terminal, start at the beginning of the line.
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000161 if (CaretEnd < Columns - 3)
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000162 CaretStart = 0;
163
Douglas Gregor99bb2922009-05-03 04:12:51 +0000164 unsigned TargetColumns = Columns - 8; // Give us extra room for the ellipses.
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000165 unsigned SourceLength = SourceLine.size();
166 bool StartIsFixed = false;
167 while (CaretEnd - CaretStart < TargetColumns) {
168 bool ExpandedRegion = false;
169 // Move the start of the interesting region left until we've
170 // pulled in something else interesting.
171 if (CaretStart && !StartIsFixed &&
172 CaretEnd - CaretStart < TargetColumns) {
173 unsigned NewStart = CaretStart;
174
175 bool BadStart = false;
176 do {
177 // Skip over any whitespace we see here; we're looking for
178 // another bit of interesting text.
179 if (NewStart)
180 --NewStart;
181 while (NewStart && isspace(SourceLine[NewStart]))
182 --NewStart;
183
184 // Skip over this bit of "interesting" text.
185 while (NewStart && !isspace(SourceLine[NewStart])) {
186 if (isClosingDelimiter(SourceLine[NewStart]))
187 StartIsFixed = true;
188 --NewStart;
189 }
190
191 // Move up to the non-whitespace character we just saw.
192 if (!StartIsFixed &&
193 isspace(SourceLine[NewStart]) &&
194 !isspace(SourceLine[NewStart + 1]))
195 ++NewStart;
196
197 // Never go back past closing delimeters, because
198 // they're unlikely to be important (and they result in
199 // weird slices). Instead, move forward to the next
200 // non-whitespace character.
201 BadStart = false;
202 if (StartIsFixed) {
203 ++NewStart;
204 while (NewStart != CaretEnd && isspace(SourceLine[NewStart]))
205 ++NewStart;
206 } else if (NewStart) {
207 // There are some characters that always signal that we've
208 // found a bad stopping place, because they always occur in
209 // the middle of or at the end of an expression. In these
210 // cases, we either keep bringing in more "interesting" text
211 // to try to get to a somewhat-complete slice of the code.
212 BadStart = ispunct(SourceLine[NewStart]);
213 }
214 } while (BadStart);
215
216 // If we're still within our limit, update the starting
217 // position within the source/caret line.
218 if (CaretEnd - NewStart <= TargetColumns && !StartIsFixed) {
219 CaretStart = NewStart;
220 ExpandedRegion = true;
221 }
222 }
223
224 // Move the end of the interesting region right until we've
225 // pulled in something else interesting.
226 if (CaretEnd != SourceLength &&
227 CaretEnd - CaretStart < TargetColumns) {
228 unsigned NewEnd = CaretEnd;
229
230 // Skip over any whitespace we see here; we're looking for
231 // another bit of interesting text.
232 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
233 ++NewEnd;
234
235 // Skip over this bit of "interesting" text.
236 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
237 ++NewEnd;
238
239 if (NewEnd - CaretStart <= TargetColumns) {
240 CaretEnd = NewEnd;
241 ExpandedRegion = true;
242 }
243
244 if (!ExpandedRegion)
245 break;
246 }
247 }
248
249 // [CaretStart, CaretEnd) is the slice we want. Update the various
250 // output lines to show only this slice, with two-space padding
251 // before the lines so that it looks nicer.
Douglas Gregor99bb2922009-05-03 04:12:51 +0000252 if (CaretEnd < SourceLine.size())
253 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000254 if (CaretEnd < CaretLine.size())
255 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000256 if (FixItInsertionLine.size() > CaretEnd)
257 FixItInsertionLine.erase(CaretEnd, std::string::npos);
258
259 if (CaretStart > 2) {
Douglas Gregor99bb2922009-05-03 04:12:51 +0000260 SourceLine.replace(0, CaretStart, " ...");
261 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000262 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor99bb2922009-05-03 04:12:51 +0000263 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000264 }
265}
266
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000267void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000268 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000269 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000270 SourceManager &SM,
271 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000272 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000273 unsigned AvoidColumn,
274 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000275 assert(!Loc.isInvalid() && "must have a valid source location here");
276
Chris Lattner3b29a182009-02-17 07:54:55 +0000277 // We always emit diagnostics about the instantiation points, not the spelling
278 // points. This more closely correlates to what the user writes.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000279 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000280 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000281 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
282 Columns);
Chris Lattner37f9ad22009-02-17 08:44:50 +0000283
Chris Lattner3272e922009-02-20 00:25:28 +0000284 // Map the location through the macro.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000285 Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
Chris Lattner3272e922009-02-20 00:25:28 +0000286
287 // Map the ranges.
288 for (unsigned i = 0; i != NumRanges; ++i) {
289 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
290 if (S.isMacroID())
291 S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
292 if (E.isMacroID())
293 E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
294 Ranges[i] = SourceRange(S, E);
295 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000296
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000297 if (ShowLocation) {
298 // Emit the file/line/column that this expansion came from.
299 OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
300 << ':';
301 if (ShowColumn)
302 OS << SM.getInstantiationColumnNumber(Loc) << ':';
303 OS << ' ';
304 }
305 OS << "note: instantiated from:\n";
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000306 AvoidColumn = 0;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000307 }
Chris Lattner34e6c262009-02-17 07:51:53 +0000308
309 // Decompose the location into a FID/Offset pair.
310 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
311 FileID FID = LocInfo.first;
312 unsigned FileOffset = LocInfo.second;
313
314 // Get information about the buffer it points into.
315 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
316 const char *BufStart = BufferInfo.first;
Chris Lattner34e6c262009-02-17 07:51:53 +0000317
318 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000319
320 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000321 const char *TokPtr = BufStart+FileOffset;
322 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
323
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000324
325 // Compute the line end. Scan forward from the error position to the end of
326 // the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000327 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000328 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000329 ++LineEnd;
330
331 // Copy the line of code into an std::string for ease of manipulation.
332 std::string SourceLine(LineStart, LineEnd);
333
334 // Create a line for the caret that is filled with spaces that is the same
335 // length as the line of source code.
336 std::string CaretLine(LineEnd-LineStart, ' ');
337
338 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000339 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000340 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
341
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000342 for (unsigned i = 0, e = NumRanges; i != e; ++i)
343 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattner34e6c262009-02-17 07:51:53 +0000344 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000345
346 // Next, insert the caret itself.
347 if (ColNo-1 < CaretLine.size())
348 CaretLine[ColNo-1] = '^';
349 else
350 CaretLine.push_back('^');
351
352 // Scan the source line, looking for tabs. If we find any, manually expand
353 // them to 8 characters and update the CaretLine to match.
354 for (unsigned i = 0; i != SourceLine.size(); ++i) {
355 if (SourceLine[i] != '\t') continue;
356
357 // Replace this tab with at least one space.
358 SourceLine[i] = ' ';
359
360 // Compute the number of spaces we need to insert.
361 unsigned NumSpaces = ((i+8)&~7) - (i+1);
362 assert(NumSpaces < 8 && "Invalid computation of space amt");
363
364 // Insert spaces into the SourceLine.
365 SourceLine.insert(i+1, NumSpaces, ' ');
366
367 // Insert spaces or ~'s into CaretLine.
368 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
369 }
370
Chris Lattner404ba8e2009-04-28 22:33:16 +0000371 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
372 // produce easily machine parsable output. Add a space before the source line
373 // and the caret to make it trivial to tell the main diagnostic line from what
374 // the user is intended to see.
375 if (PrintRangeInfo) {
376 SourceLine = ' ' + SourceLine;
377 CaretLine = ' ' + CaretLine;
378 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000379
380 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000381 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000382 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000383 Hint != LastHint; ++Hint) {
384 if (Hint->InsertionLoc.isValid()) {
385 // We have an insertion hint. Determine whether the inserted
386 // code is on the same line as the caret.
387 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner9ccffa72009-03-02 20:58:48 +0000388 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000389 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
390 SM.getLineNumber(FID, FileOffset)) {
391 // Insert the new code into the line just below the code
392 // that the user wrote.
393 unsigned HintColNo
394 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
395 unsigned LastColumnModified
396 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000397 if (LastColumnModified > FixItInsertionLine.size())
398 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000399 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000400 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000401 } else {
402 FixItInsertionLine.clear();
403 break;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000404 }
405 }
406 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000407 }
Douglas Gregor3bb30002009-02-26 21:00:50 +0000408
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000409 // If the source line is too long for our terminal, select only the
410 // "interesting" source region within that line.
411 if (Columns && SourceLine.size() > Columns)
412 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
413 Columns);
414
415 // AvoidColumn tells us which column we should avoid when printing
416 // the source line. If the source line would start at or near that
417 // column, add another line of whitespace before printing the source
418 // line. Otherwise, the source line and the diagnostic text can get
419 // jumbled together.
420 unsigned StartCol = 0;
421 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
422 if (!isspace(SourceLine[StartCol]))
423 break;
424
425 if (StartCol != SourceLine.size() &&
426 abs((int)StartCol - (int)AvoidColumn) <= 2)
427 OS << '\n';
428
429 // Finally, remove any blank spaces from the end of CaretLine.
430 while (CaretLine[CaretLine.size()-1] == ' ')
431 CaretLine.erase(CaretLine.end()-1);
432
433 // Emit what we have computed.
434 OS << SourceLine << '\n';
435 OS << CaretLine << '\n';
436
437 if (!FixItInsertionLine.empty()) {
438 if (PrintRangeInfo)
439 OS << ' ';
440 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000441 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000442}
443
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000444/// \brief Skip over whitespace in the string, starting at the given
445/// index.
446///
447/// \returns The index of the first non-whitespace character that is
448/// greater than or equal to Idx or, if no such character exists,
449/// returns the end of the string.
450static unsigned skipWhitespace(unsigned Idx,
451 const llvm::SmallVectorImpl<char> &Str,
452 unsigned Length) {
453 while (Idx < Length && isspace(Str[Idx]))
454 ++Idx;
455 return Idx;
456}
457
458/// \brief If the given character is the start of some kind of
459/// balanced punctuation (e.g., quotes or parentheses), return the
460/// character that will terminate the punctuation.
461///
462/// \returns The ending punctuation character, if any, or the NULL
463/// character if the input character does not start any punctuation.
464static inline char findMatchingPunctuation(char c) {
465 switch (c) {
466 case '\'': return '\'';
467 case '`': return '\'';
468 case '"': return '"';
469 case '(': return ')';
470 case '[': return ']';
471 case '{': return '}';
472 default: break;
473 }
474
475 return 0;
476}
477
478/// \brief Find the end of the word starting at the given offset
479/// within a string.
480///
481/// \returns the index pointing one character past the end of the
482/// word.
483unsigned findEndOfWord(unsigned Start,
484 const llvm::SmallVectorImpl<char> &Str,
485 unsigned Length, unsigned Column,
486 unsigned Columns) {
487 unsigned End = Start + 1;
488
489 // Determine if the start of the string is actually opening
490 // punctuation, e.g., a quote or parentheses.
491 char EndPunct = findMatchingPunctuation(Str[Start]);
492 if (!EndPunct) {
493 // This is a normal word. Just find the first space character.
494 while (End < Length && !isspace(Str[End]))
495 ++End;
496 return End;
497 }
498
499 // We have the start of a balanced punctuation sequence (quotes,
500 // parentheses, etc.). Determine the full sequence is.
501 llvm::SmallVector<char, 16> PunctuationEndStack;
502 PunctuationEndStack.push_back(EndPunct);
503 while (End < Length && !PunctuationEndStack.empty()) {
504 if (Str[End] == PunctuationEndStack.back())
505 PunctuationEndStack.pop_back();
506 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
507 PunctuationEndStack.push_back(SubEndPunct);
508
509 ++End;
510 }
511
512 // Find the first space character after the punctuation ended.
513 while (End < Length && !isspace(Str[End]))
514 ++End;
515
516 unsigned PunctWordLength = End - Start;
517 if (// If the word fits on this line
518 Column + PunctWordLength <= Columns ||
519 // ... or the word is "short enough" to take up the next line
520 // without too much ugly white space
521 PunctWordLength < Columns/3)
522 return End; // Take the whole thing as a single "word".
523
524 // The whole quoted/parenthesized string is too long to print as a
525 // single "word". Instead, find the "word" that starts just after
526 // the punctuation and use that end-point instead. This will recurse
527 // until it finds something small enough to consider a word.
528 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
529}
530
531/// \brief Print the given string to a stream, word-wrapping it to
532/// some number of columns in the process.
533///
534/// \brief OS the stream to which the word-wrapping string will be
535/// emitted.
536///
537/// \brief Str the string to word-wrap and output.
538///
539/// \brief Columns the number of columns to word-wrap to.
540///
541/// \brief Column the column number at which the first character of \p
542/// Str will be printed. This will be non-zero when part of the first
543/// line has already been printed.
544///
545/// \brief Indentation the number of spaces to indent any lines beyond
546/// the first line.
547///
548/// \returns true if word-wrapping was required, or false if the
549/// string fit on the first line.
550static bool PrintWordWrapped(llvm::raw_ostream &OS,
551 const llvm::SmallVectorImpl<char> &Str,
552 unsigned Columns,
553 unsigned Column = 0,
554 unsigned Indentation = WordWrapIndentation) {
555 unsigned Length = Str.size();
556
557 // If there is a newline in this message somewhere, find that
558 // newline and split the message into the part before the newline
559 // (which will be word-wrapped) and the part from the newline one
560 // (which will be emitted unchanged).
561 for (unsigned I = 0; I != Length; ++I)
562 if (Str[I] == '\n') {
563 Length = I;
564 break;
565 }
566
567 // The string used to indent each line.
568 llvm::SmallString<16> IndentStr;
569 IndentStr.assign(Indentation, ' ');
570 bool Wrapped = false;
571 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
572 WordStart = WordEnd) {
573 // Find the beginning of the next word.
574 WordStart = skipWhitespace(WordStart, Str, Length);
575 if (WordStart == Length)
576 break;
577
578 // Find the end of this word.
579 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
580
581 // Does this word fit on the current line?
582 unsigned WordLength = WordEnd - WordStart;
583 if (Column + WordLength < Columns) {
584 // This word fits on the current line; print it there.
585 if (WordStart) {
586 OS << ' ';
587 Column += 1;
588 }
589 OS.write(&Str[WordStart], WordLength);
590 Column += WordLength;
591 continue;
592 }
593
594 // This word does not fit on the current line, so wrap to the next
595 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000596 OS << '\n';
597 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000598 OS.write(&Str[WordStart], WordLength);
599 Column = Indentation + WordLength;
600 Wrapped = true;
601 }
602
603 if (Length == Str.size())
604 return Wrapped; // We're done.
605
606 // There is a newline in the message, followed by something that
607 // will not be word-wrapped. Print that.
608 OS.write(&Str[Length], Str.size() - Length);
609 return true;
610}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000611
Chris Lattner6948ae62008-11-18 07:04:44 +0000612void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
613 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000614 // Keeps track of the the starting position of the location
615 // information (e.g., "foo.c:10:4:") that precedes the error
616 // message. We use this information to determine how long the
617 // file+line+column number prefix is.
618 uint64_t StartOfLocationInfo = OS.tell();
619
Chris Lattner836774b2009-01-27 07:57:44 +0000620 // If the location is specified, print out a file/line/col and include trace
621 // if enabled.
622 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000623 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000624 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
625 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000626
627 // First, if this diagnostic is not in the main file, print out the
628 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000629 if (LastWarningLoc != PLoc.getIncludeLoc()) {
630 LastWarningLoc = PLoc.getIncludeLoc();
631 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000632 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000633 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000634
Chris Lattner836774b2009-01-27 07:57:44 +0000635 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000636 if (ShowLocation) {
637 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000638 if (ShowColumn)
639 if (unsigned ColNo = PLoc.getColumn())
640 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000641
642 if (PrintRangeInfo && Info.getNumRanges()) {
643 FileID CaretFileID =
644 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
645 bool PrintedRange = false;
646
647 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000648 // Ignore invalid ranges.
649 if (!Info.getRange(i).isValid()) continue;
650
Chris Lattner695a4f52009-03-13 01:08:23 +0000651 SourceLocation B = Info.getRange(i).getBegin();
652 SourceLocation E = Info.getRange(i).getEnd();
653 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
654
655 E = SM.getInstantiationLoc(E);
656 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
657
658 // If the start or end of the range is in another file, just discard
659 // it.
660 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
661 continue;
662
663 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000664 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000665
666 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
667 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
668 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
669 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
670 PrintedRange = true;
671 }
672
673 if (PrintedRange)
674 OS << ':';
675 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000676 OS << ' ';
677 }
Chris Lattner4b009652007-07-25 00:24:17 +0000678 }
679
680 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000681 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000682 case Diagnostic::Note: OS << "note: "; break;
683 case Diagnostic::Warning: OS << "warning: "; break;
684 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000685 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000686 }
687
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000688 llvm::SmallString<100> OutStr;
689 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000690
691 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000692 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
693 OutStr += " [-W";
694 OutStr += Opt;
695 OutStr += ']';
696 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000697
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000698 bool WordWrapped = false;
699 if (MessageLength) {
700 // We will be word-wrapping the error message, so compute the
701 // column number where we currently are (after printing the
702 // location information).
703 unsigned Column = OS.tell() - StartOfLocationInfo;
704 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
705 } else {
706 OS.write(OutStr.begin(), OutStr.size());
707 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000708 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000709
Douglas Gregor56d25a72009-03-10 20:44:00 +0000710 // If caret diagnostics are enabled and we have location, we want to
711 // emit the caret. However, we only do this if the location moved
712 // from the last diagnostic, if the last diagnostic was a note that
713 // was part of a different warning or error diagnostic, or if the
714 // diagnostic has ranges. We don't want to emit the same caret
715 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000716 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000717 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000718 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000719 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000720 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000721 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000722 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000723
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000724 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000725 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000726 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000727 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000728 for (unsigned i = 0; i != NumRanges; ++i)
729 Ranges[i] = Info.getRange(i);
730
Douglas Gregor3bb30002009-02-26 21:00:50 +0000731 unsigned NumHints = Info.getNumCodeModificationHints();
732 for (unsigned idx = 0; idx < NumHints; ++idx) {
733 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
734 if (Hint.RemoveRange.isValid()) {
735 assert(NumRanges < 20 && "Out of space");
736 Ranges[NumRanges++] = Hint.RemoveRange;
737 }
738 }
739
740 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
741 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000742 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000743 WordWrapped? WordWrapIndentation : 0,
744 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000745 }
Chris Lattner92a33532008-11-19 06:56:25 +0000746
747 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000748}