blob: bcf30a5f561827167a38927049e469dae3585da9 [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;
135
136 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
137 // parts of the caret line. While this slice is smaller than the
138 // number of columns we have, try to grow the slice to encompass
139 // more context.
140
141 // If the end of the interesting region comes before we run out of
142 // space in the terminal, start at the beginning of the line.
143 if (CaretEnd < Columns)
144 CaretStart = 0;
145
Douglas Gregor99bb2922009-05-03 04:12:51 +0000146 unsigned TargetColumns = Columns - 8; // Give us extra room for the ellipses.
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000147 unsigned SourceLength = SourceLine.size();
148 bool StartIsFixed = false;
149 while (CaretEnd - CaretStart < TargetColumns) {
150 bool ExpandedRegion = false;
151 // Move the start of the interesting region left until we've
152 // pulled in something else interesting.
153 if (CaretStart && !StartIsFixed &&
154 CaretEnd - CaretStart < TargetColumns) {
155 unsigned NewStart = CaretStart;
156
157 bool BadStart = false;
158 do {
159 // Skip over any whitespace we see here; we're looking for
160 // another bit of interesting text.
161 if (NewStart)
162 --NewStart;
163 while (NewStart && isspace(SourceLine[NewStart]))
164 --NewStart;
165
166 // Skip over this bit of "interesting" text.
167 while (NewStart && !isspace(SourceLine[NewStart])) {
168 if (isClosingDelimiter(SourceLine[NewStart]))
169 StartIsFixed = true;
170 --NewStart;
171 }
172
173 // Move up to the non-whitespace character we just saw.
174 if (!StartIsFixed &&
175 isspace(SourceLine[NewStart]) &&
176 !isspace(SourceLine[NewStart + 1]))
177 ++NewStart;
178
179 // Never go back past closing delimeters, because
180 // they're unlikely to be important (and they result in
181 // weird slices). Instead, move forward to the next
182 // non-whitespace character.
183 BadStart = false;
184 if (StartIsFixed) {
185 ++NewStart;
186 while (NewStart != CaretEnd && isspace(SourceLine[NewStart]))
187 ++NewStart;
188 } else if (NewStart) {
189 // There are some characters that always signal that we've
190 // found a bad stopping place, because they always occur in
191 // the middle of or at the end of an expression. In these
192 // cases, we either keep bringing in more "interesting" text
193 // to try to get to a somewhat-complete slice of the code.
194 BadStart = ispunct(SourceLine[NewStart]);
195 }
196 } while (BadStart);
197
198 // If we're still within our limit, update the starting
199 // position within the source/caret line.
200 if (CaretEnd - NewStart <= TargetColumns && !StartIsFixed) {
201 CaretStart = NewStart;
202 ExpandedRegion = true;
203 }
204 }
205
206 // Move the end of the interesting region right until we've
207 // pulled in something else interesting.
208 if (CaretEnd != SourceLength &&
209 CaretEnd - CaretStart < TargetColumns) {
210 unsigned NewEnd = CaretEnd;
211
212 // Skip over any whitespace we see here; we're looking for
213 // another bit of interesting text.
214 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
215 ++NewEnd;
216
217 // Skip over this bit of "interesting" text.
218 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
219 ++NewEnd;
220
221 if (NewEnd - CaretStart <= TargetColumns) {
222 CaretEnd = NewEnd;
223 ExpandedRegion = true;
224 }
225
226 if (!ExpandedRegion)
227 break;
228 }
229 }
230
231 // [CaretStart, CaretEnd) is the slice we want. Update the various
232 // output lines to show only this slice, with two-space padding
233 // before the lines so that it looks nicer.
Douglas Gregor99bb2922009-05-03 04:12:51 +0000234 if (CaretEnd < SourceLine.size())
235 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000236 CaretLine.erase(CaretEnd, std::string::npos);
237 if (FixItInsertionLine.size() > CaretEnd)
238 FixItInsertionLine.erase(CaretEnd, std::string::npos);
239
240 if (CaretStart > 2) {
Douglas Gregor99bb2922009-05-03 04:12:51 +0000241 SourceLine.replace(0, CaretStart, " ...");
242 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000243 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor99bb2922009-05-03 04:12:51 +0000244 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000245 }
246}
247
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000248void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000249 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000250 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000251 SourceManager &SM,
252 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000253 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000254 unsigned AvoidColumn,
255 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000256 assert(!Loc.isInvalid() && "must have a valid source location here");
257
Chris Lattner3b29a182009-02-17 07:54:55 +0000258 // We always emit diagnostics about the instantiation points, not the spelling
259 // points. This more closely correlates to what the user writes.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000260 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000261 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000262 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
263 Columns);
Chris Lattner37f9ad22009-02-17 08:44:50 +0000264
Chris Lattner3272e922009-02-20 00:25:28 +0000265 // Map the location through the macro.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000266 Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
Chris Lattner3272e922009-02-20 00:25:28 +0000267
268 // Map the ranges.
269 for (unsigned i = 0; i != NumRanges; ++i) {
270 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
271 if (S.isMacroID())
272 S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
273 if (E.isMacroID())
274 E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
275 Ranges[i] = SourceRange(S, E);
276 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000277
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000278 if (ShowLocation) {
279 // Emit the file/line/column that this expansion came from.
280 OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
281 << ':';
282 if (ShowColumn)
283 OS << SM.getInstantiationColumnNumber(Loc) << ':';
284 OS << ' ';
285 }
286 OS << "note: instantiated from:\n";
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000287 AvoidColumn = 0;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000288 }
Chris Lattner34e6c262009-02-17 07:51:53 +0000289
290 // Decompose the location into a FID/Offset pair.
291 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
292 FileID FID = LocInfo.first;
293 unsigned FileOffset = LocInfo.second;
294
295 // Get information about the buffer it points into.
296 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
297 const char *BufStart = BufferInfo.first;
Chris Lattner34e6c262009-02-17 07:51:53 +0000298
299 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000300
301 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000302 const char *TokPtr = BufStart+FileOffset;
303 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
304
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000305
306 // Compute the line end. Scan forward from the error position to the end of
307 // the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000308 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000309 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000310 ++LineEnd;
311
312 // Copy the line of code into an std::string for ease of manipulation.
313 std::string SourceLine(LineStart, LineEnd);
314
315 // Create a line for the caret that is filled with spaces that is the same
316 // length as the line of source code.
317 std::string CaretLine(LineEnd-LineStart, ' ');
318
319 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000320 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000321 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
322
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000323 for (unsigned i = 0, e = NumRanges; i != e; ++i)
324 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattner34e6c262009-02-17 07:51:53 +0000325 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000326
327 // Next, insert the caret itself.
328 if (ColNo-1 < CaretLine.size())
329 CaretLine[ColNo-1] = '^';
330 else
331 CaretLine.push_back('^');
332
333 // Scan the source line, looking for tabs. If we find any, manually expand
334 // them to 8 characters and update the CaretLine to match.
335 for (unsigned i = 0; i != SourceLine.size(); ++i) {
336 if (SourceLine[i] != '\t') continue;
337
338 // Replace this tab with at least one space.
339 SourceLine[i] = ' ';
340
341 // Compute the number of spaces we need to insert.
342 unsigned NumSpaces = ((i+8)&~7) - (i+1);
343 assert(NumSpaces < 8 && "Invalid computation of space amt");
344
345 // Insert spaces into the SourceLine.
346 SourceLine.insert(i+1, NumSpaces, ' ');
347
348 // Insert spaces or ~'s into CaretLine.
349 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
350 }
351
Chris Lattner404ba8e2009-04-28 22:33:16 +0000352 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
353 // produce easily machine parsable output. Add a space before the source line
354 // and the caret to make it trivial to tell the main diagnostic line from what
355 // the user is intended to see.
356 if (PrintRangeInfo) {
357 SourceLine = ' ' + SourceLine;
358 CaretLine = ' ' + CaretLine;
359 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000360
361 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000362 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000363 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000364 Hint != LastHint; ++Hint) {
365 if (Hint->InsertionLoc.isValid()) {
366 // We have an insertion hint. Determine whether the inserted
367 // code is on the same line as the caret.
368 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner9ccffa72009-03-02 20:58:48 +0000369 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000370 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
371 SM.getLineNumber(FID, FileOffset)) {
372 // Insert the new code into the line just below the code
373 // that the user wrote.
374 unsigned HintColNo
375 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
376 unsigned LastColumnModified
377 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000378 if (LastColumnModified > FixItInsertionLine.size())
379 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000380 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000381 FixItInsertionLine.begin() + HintColNo - 1);
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,
391 Columns);
392
393 // AvoidColumn tells us which column we should avoid when printing
394 // the source line. If the source line would start at or near that
395 // column, add another line of whitespace before printing the source
396 // line. Otherwise, the source line and the diagnostic text can get
397 // jumbled together.
398 unsigned StartCol = 0;
399 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
400 if (!isspace(SourceLine[StartCol]))
401 break;
402
403 if (StartCol != SourceLine.size() &&
404 abs((int)StartCol - (int)AvoidColumn) <= 2)
405 OS << '\n';
406
407 // Finally, remove any blank spaces from the end of CaretLine.
408 while (CaretLine[CaretLine.size()-1] == ' ')
409 CaretLine.erase(CaretLine.end()-1);
410
411 // Emit what we have computed.
412 OS << SourceLine << '\n';
413 OS << CaretLine << '\n';
414
415 if (!FixItInsertionLine.empty()) {
416 if (PrintRangeInfo)
417 OS << ' ';
418 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000419 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000420}
421
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000422/// \brief Skip over whitespace in the string, starting at the given
423/// index.
424///
425/// \returns The index of the first non-whitespace character that is
426/// greater than or equal to Idx or, if no such character exists,
427/// returns the end of the string.
428static unsigned skipWhitespace(unsigned Idx,
429 const llvm::SmallVectorImpl<char> &Str,
430 unsigned Length) {
431 while (Idx < Length && isspace(Str[Idx]))
432 ++Idx;
433 return Idx;
434}
435
436/// \brief If the given character is the start of some kind of
437/// balanced punctuation (e.g., quotes or parentheses), return the
438/// character that will terminate the punctuation.
439///
440/// \returns The ending punctuation character, if any, or the NULL
441/// character if the input character does not start any punctuation.
442static inline char findMatchingPunctuation(char c) {
443 switch (c) {
444 case '\'': return '\'';
445 case '`': return '\'';
446 case '"': return '"';
447 case '(': return ')';
448 case '[': return ']';
449 case '{': return '}';
450 default: break;
451 }
452
453 return 0;
454}
455
456/// \brief Find the end of the word starting at the given offset
457/// within a string.
458///
459/// \returns the index pointing one character past the end of the
460/// word.
461unsigned findEndOfWord(unsigned Start,
462 const llvm::SmallVectorImpl<char> &Str,
463 unsigned Length, unsigned Column,
464 unsigned Columns) {
465 unsigned End = Start + 1;
466
467 // Determine if the start of the string is actually opening
468 // punctuation, e.g., a quote or parentheses.
469 char EndPunct = findMatchingPunctuation(Str[Start]);
470 if (!EndPunct) {
471 // This is a normal word. Just find the first space character.
472 while (End < Length && !isspace(Str[End]))
473 ++End;
474 return End;
475 }
476
477 // We have the start of a balanced punctuation sequence (quotes,
478 // parentheses, etc.). Determine the full sequence is.
479 llvm::SmallVector<char, 16> PunctuationEndStack;
480 PunctuationEndStack.push_back(EndPunct);
481 while (End < Length && !PunctuationEndStack.empty()) {
482 if (Str[End] == PunctuationEndStack.back())
483 PunctuationEndStack.pop_back();
484 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
485 PunctuationEndStack.push_back(SubEndPunct);
486
487 ++End;
488 }
489
490 // Find the first space character after the punctuation ended.
491 while (End < Length && !isspace(Str[End]))
492 ++End;
493
494 unsigned PunctWordLength = End - Start;
495 if (// If the word fits on this line
496 Column + PunctWordLength <= Columns ||
497 // ... or the word is "short enough" to take up the next line
498 // without too much ugly white space
499 PunctWordLength < Columns/3)
500 return End; // Take the whole thing as a single "word".
501
502 // The whole quoted/parenthesized string is too long to print as a
503 // single "word". Instead, find the "word" that starts just after
504 // the punctuation and use that end-point instead. This will recurse
505 // until it finds something small enough to consider a word.
506 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
507}
508
509/// \brief Print the given string to a stream, word-wrapping it to
510/// some number of columns in the process.
511///
512/// \brief OS the stream to which the word-wrapping string will be
513/// emitted.
514///
515/// \brief Str the string to word-wrap and output.
516///
517/// \brief Columns the number of columns to word-wrap to.
518///
519/// \brief Column the column number at which the first character of \p
520/// Str will be printed. This will be non-zero when part of the first
521/// line has already been printed.
522///
523/// \brief Indentation the number of spaces to indent any lines beyond
524/// the first line.
525///
526/// \returns true if word-wrapping was required, or false if the
527/// string fit on the first line.
528static bool PrintWordWrapped(llvm::raw_ostream &OS,
529 const llvm::SmallVectorImpl<char> &Str,
530 unsigned Columns,
531 unsigned Column = 0,
532 unsigned Indentation = WordWrapIndentation) {
533 unsigned Length = Str.size();
534
535 // If there is a newline in this message somewhere, find that
536 // newline and split the message into the part before the newline
537 // (which will be word-wrapped) and the part from the newline one
538 // (which will be emitted unchanged).
539 for (unsigned I = 0; I != Length; ++I)
540 if (Str[I] == '\n') {
541 Length = I;
542 break;
543 }
544
545 // The string used to indent each line.
546 llvm::SmallString<16> IndentStr;
547 IndentStr.assign(Indentation, ' ');
548 bool Wrapped = false;
549 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
550 WordStart = WordEnd) {
551 // Find the beginning of the next word.
552 WordStart = skipWhitespace(WordStart, Str, Length);
553 if (WordStart == Length)
554 break;
555
556 // Find the end of this word.
557 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
558
559 // Does this word fit on the current line?
560 unsigned WordLength = WordEnd - WordStart;
561 if (Column + WordLength < Columns) {
562 // This word fits on the current line; print it there.
563 if (WordStart) {
564 OS << ' ';
565 Column += 1;
566 }
567 OS.write(&Str[WordStart], WordLength);
568 Column += WordLength;
569 continue;
570 }
571
572 // This word does not fit on the current line, so wrap to the next
573 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000574 OS << '\n';
575 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000576 OS.write(&Str[WordStart], WordLength);
577 Column = Indentation + WordLength;
578 Wrapped = true;
579 }
580
581 if (Length == Str.size())
582 return Wrapped; // We're done.
583
584 // There is a newline in the message, followed by something that
585 // will not be word-wrapped. Print that.
586 OS.write(&Str[Length], Str.size() - Length);
587 return true;
588}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000589
Chris Lattner6948ae62008-11-18 07:04:44 +0000590void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
591 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000592 // Keeps track of the the starting position of the location
593 // information (e.g., "foo.c:10:4:") that precedes the error
594 // message. We use this information to determine how long the
595 // file+line+column number prefix is.
596 uint64_t StartOfLocationInfo = OS.tell();
597
Chris Lattner836774b2009-01-27 07:57:44 +0000598 // If the location is specified, print out a file/line/col and include trace
599 // if enabled.
600 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000601 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000602 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
603 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000604
605 // First, if this diagnostic is not in the main file, print out the
606 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000607 if (LastWarningLoc != PLoc.getIncludeLoc()) {
608 LastWarningLoc = PLoc.getIncludeLoc();
609 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000610 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000611 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000612
Chris Lattner836774b2009-01-27 07:57:44 +0000613 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000614 if (ShowLocation) {
615 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000616 if (ShowColumn)
617 if (unsigned ColNo = PLoc.getColumn())
618 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000619
620 if (PrintRangeInfo && Info.getNumRanges()) {
621 FileID CaretFileID =
622 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
623 bool PrintedRange = false;
624
625 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000626 // Ignore invalid ranges.
627 if (!Info.getRange(i).isValid()) continue;
628
Chris Lattner695a4f52009-03-13 01:08:23 +0000629 SourceLocation B = Info.getRange(i).getBegin();
630 SourceLocation E = Info.getRange(i).getEnd();
631 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
632
633 E = SM.getInstantiationLoc(E);
634 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
635
636 // If the start or end of the range is in another file, just discard
637 // it.
638 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
639 continue;
640
641 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000642 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000643
644 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
645 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
646 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
647 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
648 PrintedRange = true;
649 }
650
651 if (PrintedRange)
652 OS << ':';
653 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000654 OS << ' ';
655 }
Chris Lattner4b009652007-07-25 00:24:17 +0000656 }
657
658 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000659 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000660 case Diagnostic::Note: OS << "note: "; break;
661 case Diagnostic::Warning: OS << "warning: "; break;
662 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000663 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000664 }
665
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000666 llvm::SmallString<100> OutStr;
667 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000668
669 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000670 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
671 OutStr += " [-W";
672 OutStr += Opt;
673 OutStr += ']';
674 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000675
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000676 bool WordWrapped = false;
677 if (MessageLength) {
678 // We will be word-wrapping the error message, so compute the
679 // column number where we currently are (after printing the
680 // location information).
681 unsigned Column = OS.tell() - StartOfLocationInfo;
682 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
683 } else {
684 OS.write(OutStr.begin(), OutStr.size());
685 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000686 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000687
Douglas Gregor56d25a72009-03-10 20:44:00 +0000688 // If caret diagnostics are enabled and we have location, we want to
689 // emit the caret. However, we only do this if the location moved
690 // from the last diagnostic, if the last diagnostic was a note that
691 // was part of a different warning or error diagnostic, or if the
692 // diagnostic has ranges. We don't want to emit the same caret
693 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000694 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000695 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000696 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000697 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000698 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000699 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000700 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000701
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000702 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000703 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000704 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000705 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000706 for (unsigned i = 0; i != NumRanges; ++i)
707 Ranges[i] = Info.getRange(i);
708
Douglas Gregor3bb30002009-02-26 21:00:50 +0000709 unsigned NumHints = Info.getNumCodeModificationHints();
710 for (unsigned idx = 0; idx < NumHints; ++idx) {
711 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
712 if (Hint.RemoveRange.isValid()) {
713 assert(NumRanges < 20 && "Out of space");
714 Ranges[NumRanges++] = Hint.RemoveRange;
715 }
716 }
717
718 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
719 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000720 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000721 WordWrapped? WordWrapIndentation : 0,
722 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000723 }
Chris Lattner92a33532008-11-19 06:56:25 +0000724
725 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000726}