blob: b8c10b536baba4fccde247291089c304bd4bcc3b [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
146 unsigned TargetColumns = Columns - 4; // Give us a little extra room.
147 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.
234 SourceLine.erase(CaretEnd, std::string::npos);
235 CaretLine.erase(CaretEnd, std::string::npos);
236 if (FixItInsertionLine.size() > CaretEnd)
237 FixItInsertionLine.erase(CaretEnd, std::string::npos);
238
239 if (CaretStart > 2) {
240 SourceLine.replace(0, CaretStart, " ");
241 CaretLine.replace(0, CaretStart, " ");
242 if (FixItInsertionLine.size() >= CaretStart)
243 FixItInsertionLine.replace(0, CaretStart, " ");
244 }
245}
246
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000247void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000248 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000249 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000250 SourceManager &SM,
251 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000252 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000253 unsigned AvoidColumn,
254 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000255 assert(!Loc.isInvalid() && "must have a valid source location here");
256
Chris Lattner3b29a182009-02-17 07:54:55 +0000257 // We always emit diagnostics about the instantiation points, not the spelling
258 // points. This more closely correlates to what the user writes.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000259 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000260 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000261 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
262 Columns);
Chris Lattner37f9ad22009-02-17 08:44:50 +0000263
Chris Lattner3272e922009-02-20 00:25:28 +0000264 // Map the location through the macro.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000265 Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
Chris Lattner3272e922009-02-20 00:25:28 +0000266
267 // Map the ranges.
268 for (unsigned i = 0; i != NumRanges; ++i) {
269 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
270 if (S.isMacroID())
271 S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
272 if (E.isMacroID())
273 E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
274 Ranges[i] = SourceRange(S, E);
275 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000276
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000277 if (ShowLocation) {
278 // Emit the file/line/column that this expansion came from.
279 OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
280 << ':';
281 if (ShowColumn)
282 OS << SM.getInstantiationColumnNumber(Loc) << ':';
283 OS << ' ';
284 }
285 OS << "note: instantiated from:\n";
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000286 AvoidColumn = 0;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000287 }
Chris Lattner34e6c262009-02-17 07:51:53 +0000288
289 // Decompose the location into a FID/Offset pair.
290 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
291 FileID FID = LocInfo.first;
292 unsigned FileOffset = LocInfo.second;
293
294 // Get information about the buffer it points into.
295 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
296 const char *BufStart = BufferInfo.first;
Chris Lattner34e6c262009-02-17 07:51:53 +0000297
298 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000299
300 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000301 const char *TokPtr = BufStart+FileOffset;
302 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
303
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000304
305 // Compute the line end. Scan forward from the error position to the end of
306 // the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000307 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000308 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000309 ++LineEnd;
310
311 // Copy the line of code into an std::string for ease of manipulation.
312 std::string SourceLine(LineStart, LineEnd);
313
314 // Create a line for the caret that is filled with spaces that is the same
315 // length as the line of source code.
316 std::string CaretLine(LineEnd-LineStart, ' ');
317
318 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000319 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000320 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
321
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000322 for (unsigned i = 0, e = NumRanges; i != e; ++i)
323 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattner34e6c262009-02-17 07:51:53 +0000324 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000325
326 // Next, insert the caret itself.
327 if (ColNo-1 < CaretLine.size())
328 CaretLine[ColNo-1] = '^';
329 else
330 CaretLine.push_back('^');
331
332 // Scan the source line, looking for tabs. If we find any, manually expand
333 // them to 8 characters and update the CaretLine to match.
334 for (unsigned i = 0; i != SourceLine.size(); ++i) {
335 if (SourceLine[i] != '\t') continue;
336
337 // Replace this tab with at least one space.
338 SourceLine[i] = ' ';
339
340 // Compute the number of spaces we need to insert.
341 unsigned NumSpaces = ((i+8)&~7) - (i+1);
342 assert(NumSpaces < 8 && "Invalid computation of space amt");
343
344 // Insert spaces into the SourceLine.
345 SourceLine.insert(i+1, NumSpaces, ' ');
346
347 // Insert spaces or ~'s into CaretLine.
348 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
349 }
350
Chris Lattner404ba8e2009-04-28 22:33:16 +0000351 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
352 // produce easily machine parsable output. Add a space before the source line
353 // and the caret to make it trivial to tell the main diagnostic line from what
354 // the user is intended to see.
355 if (PrintRangeInfo) {
356 SourceLine = ' ' + SourceLine;
357 CaretLine = ' ' + CaretLine;
358 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000359
360 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000361 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000362 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000363 Hint != LastHint; ++Hint) {
364 if (Hint->InsertionLoc.isValid()) {
365 // We have an insertion hint. Determine whether the inserted
366 // code is on the same line as the caret.
367 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner9ccffa72009-03-02 20:58:48 +0000368 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000369 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
370 SM.getLineNumber(FID, FileOffset)) {
371 // Insert the new code into the line just below the code
372 // that the user wrote.
373 unsigned HintColNo
374 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
375 unsigned LastColumnModified
376 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000377 if (LastColumnModified > FixItInsertionLine.size())
378 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000379 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000380 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000381 }
382 }
383 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000384 }
Douglas Gregor3bb30002009-02-26 21:00:50 +0000385
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000386 // If the source line is too long for our terminal, select only the
387 // "interesting" source region within that line.
388 if (Columns && SourceLine.size() > Columns)
389 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
390 Columns);
391
392 // AvoidColumn tells us which column we should avoid when printing
393 // the source line. If the source line would start at or near that
394 // column, add another line of whitespace before printing the source
395 // line. Otherwise, the source line and the diagnostic text can get
396 // jumbled together.
397 unsigned StartCol = 0;
398 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
399 if (!isspace(SourceLine[StartCol]))
400 break;
401
402 if (StartCol != SourceLine.size() &&
403 abs((int)StartCol - (int)AvoidColumn) <= 2)
404 OS << '\n';
405
406 // Finally, remove any blank spaces from the end of CaretLine.
407 while (CaretLine[CaretLine.size()-1] == ' ')
408 CaretLine.erase(CaretLine.end()-1);
409
410 // Emit what we have computed.
411 OS << SourceLine << '\n';
412 OS << CaretLine << '\n';
413
414 if (!FixItInsertionLine.empty()) {
415 if (PrintRangeInfo)
416 OS << ' ';
417 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000418 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000419}
420
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000421/// \brief Skip over whitespace in the string, starting at the given
422/// index.
423///
424/// \returns The index of the first non-whitespace character that is
425/// greater than or equal to Idx or, if no such character exists,
426/// returns the end of the string.
427static unsigned skipWhitespace(unsigned Idx,
428 const llvm::SmallVectorImpl<char> &Str,
429 unsigned Length) {
430 while (Idx < Length && isspace(Str[Idx]))
431 ++Idx;
432 return Idx;
433}
434
435/// \brief If the given character is the start of some kind of
436/// balanced punctuation (e.g., quotes or parentheses), return the
437/// character that will terminate the punctuation.
438///
439/// \returns The ending punctuation character, if any, or the NULL
440/// character if the input character does not start any punctuation.
441static inline char findMatchingPunctuation(char c) {
442 switch (c) {
443 case '\'': return '\'';
444 case '`': return '\'';
445 case '"': return '"';
446 case '(': return ')';
447 case '[': return ']';
448 case '{': return '}';
449 default: break;
450 }
451
452 return 0;
453}
454
455/// \brief Find the end of the word starting at the given offset
456/// within a string.
457///
458/// \returns the index pointing one character past the end of the
459/// word.
460unsigned findEndOfWord(unsigned Start,
461 const llvm::SmallVectorImpl<char> &Str,
462 unsigned Length, unsigned Column,
463 unsigned Columns) {
464 unsigned End = Start + 1;
465
466 // Determine if the start of the string is actually opening
467 // punctuation, e.g., a quote or parentheses.
468 char EndPunct = findMatchingPunctuation(Str[Start]);
469 if (!EndPunct) {
470 // This is a normal word. Just find the first space character.
471 while (End < Length && !isspace(Str[End]))
472 ++End;
473 return End;
474 }
475
476 // We have the start of a balanced punctuation sequence (quotes,
477 // parentheses, etc.). Determine the full sequence is.
478 llvm::SmallVector<char, 16> PunctuationEndStack;
479 PunctuationEndStack.push_back(EndPunct);
480 while (End < Length && !PunctuationEndStack.empty()) {
481 if (Str[End] == PunctuationEndStack.back())
482 PunctuationEndStack.pop_back();
483 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
484 PunctuationEndStack.push_back(SubEndPunct);
485
486 ++End;
487 }
488
489 // Find the first space character after the punctuation ended.
490 while (End < Length && !isspace(Str[End]))
491 ++End;
492
493 unsigned PunctWordLength = End - Start;
494 if (// If the word fits on this line
495 Column + PunctWordLength <= Columns ||
496 // ... or the word is "short enough" to take up the next line
497 // without too much ugly white space
498 PunctWordLength < Columns/3)
499 return End; // Take the whole thing as a single "word".
500
501 // The whole quoted/parenthesized string is too long to print as a
502 // single "word". Instead, find the "word" that starts just after
503 // the punctuation and use that end-point instead. This will recurse
504 // until it finds something small enough to consider a word.
505 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
506}
507
508/// \brief Print the given string to a stream, word-wrapping it to
509/// some number of columns in the process.
510///
511/// \brief OS the stream to which the word-wrapping string will be
512/// emitted.
513///
514/// \brief Str the string to word-wrap and output.
515///
516/// \brief Columns the number of columns to word-wrap to.
517///
518/// \brief Column the column number at which the first character of \p
519/// Str will be printed. This will be non-zero when part of the first
520/// line has already been printed.
521///
522/// \brief Indentation the number of spaces to indent any lines beyond
523/// the first line.
524///
525/// \returns true if word-wrapping was required, or false if the
526/// string fit on the first line.
527static bool PrintWordWrapped(llvm::raw_ostream &OS,
528 const llvm::SmallVectorImpl<char> &Str,
529 unsigned Columns,
530 unsigned Column = 0,
531 unsigned Indentation = WordWrapIndentation) {
532 unsigned Length = Str.size();
533
534 // If there is a newline in this message somewhere, find that
535 // newline and split the message into the part before the newline
536 // (which will be word-wrapped) and the part from the newline one
537 // (which will be emitted unchanged).
538 for (unsigned I = 0; I != Length; ++I)
539 if (Str[I] == '\n') {
540 Length = I;
541 break;
542 }
543
544 // The string used to indent each line.
545 llvm::SmallString<16> IndentStr;
546 IndentStr.assign(Indentation, ' ');
547 bool Wrapped = false;
548 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
549 WordStart = WordEnd) {
550 // Find the beginning of the next word.
551 WordStart = skipWhitespace(WordStart, Str, Length);
552 if (WordStart == Length)
553 break;
554
555 // Find the end of this word.
556 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
557
558 // Does this word fit on the current line?
559 unsigned WordLength = WordEnd - WordStart;
560 if (Column + WordLength < Columns) {
561 // This word fits on the current line; print it there.
562 if (WordStart) {
563 OS << ' ';
564 Column += 1;
565 }
566 OS.write(&Str[WordStart], WordLength);
567 Column += WordLength;
568 continue;
569 }
570
571 // This word does not fit on the current line, so wrap to the next
572 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000573 OS << '\n';
574 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000575 OS.write(&Str[WordStart], WordLength);
576 Column = Indentation + WordLength;
577 Wrapped = true;
578 }
579
580 if (Length == Str.size())
581 return Wrapped; // We're done.
582
583 // There is a newline in the message, followed by something that
584 // will not be word-wrapped. Print that.
585 OS.write(&Str[Length], Str.size() - Length);
586 return true;
587}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000588
Chris Lattner6948ae62008-11-18 07:04:44 +0000589void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
590 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000591 // Keeps track of the the starting position of the location
592 // information (e.g., "foo.c:10:4:") that precedes the error
593 // message. We use this information to determine how long the
594 // file+line+column number prefix is.
595 uint64_t StartOfLocationInfo = OS.tell();
596
Chris Lattner836774b2009-01-27 07:57:44 +0000597 // If the location is specified, print out a file/line/col and include trace
598 // if enabled.
599 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000600 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000601 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
602 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000603
604 // First, if this diagnostic is not in the main file, print out the
605 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000606 if (LastWarningLoc != PLoc.getIncludeLoc()) {
607 LastWarningLoc = PLoc.getIncludeLoc();
608 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000609 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000610 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000611
Chris Lattner836774b2009-01-27 07:57:44 +0000612 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000613 if (ShowLocation) {
614 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000615 if (ShowColumn)
616 if (unsigned ColNo = PLoc.getColumn())
617 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000618
619 if (PrintRangeInfo && Info.getNumRanges()) {
620 FileID CaretFileID =
621 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
622 bool PrintedRange = false;
623
624 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000625 // Ignore invalid ranges.
626 if (!Info.getRange(i).isValid()) continue;
627
Chris Lattner695a4f52009-03-13 01:08:23 +0000628 SourceLocation B = Info.getRange(i).getBegin();
629 SourceLocation E = Info.getRange(i).getEnd();
630 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
631
632 E = SM.getInstantiationLoc(E);
633 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
634
635 // If the start or end of the range is in another file, just discard
636 // it.
637 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
638 continue;
639
640 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000641 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000642
643 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
644 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
645 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
646 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
647 PrintedRange = true;
648 }
649
650 if (PrintedRange)
651 OS << ':';
652 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000653 OS << ' ';
654 }
Chris Lattner4b009652007-07-25 00:24:17 +0000655 }
656
657 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000658 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000659 case Diagnostic::Note: OS << "note: "; break;
660 case Diagnostic::Warning: OS << "warning: "; break;
661 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000662 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000663 }
664
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000665 llvm::SmallString<100> OutStr;
666 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000667
668 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000669 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
670 OutStr += " [-W";
671 OutStr += Opt;
672 OutStr += ']';
673 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000674
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000675 bool WordWrapped = false;
676 if (MessageLength) {
677 // We will be word-wrapping the error message, so compute the
678 // column number where we currently are (after printing the
679 // location information).
680 unsigned Column = OS.tell() - StartOfLocationInfo;
681 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
682 } else {
683 OS.write(OutStr.begin(), OutStr.size());
684 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000685 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000686
Douglas Gregor56d25a72009-03-10 20:44:00 +0000687 // If caret diagnostics are enabled and we have location, we want to
688 // emit the caret. However, we only do this if the location moved
689 // from the last diagnostic, if the last diagnostic was a note that
690 // was part of a different warning or error diagnostic, or if the
691 // diagnostic has ranges. We don't want to emit the same caret
692 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000693 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000694 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000695 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000696 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000697 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000698 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000699 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000700
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000701 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000702 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000703 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000704 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000705 for (unsigned i = 0; i != NumRanges; ++i)
706 Ranges[i] = Info.getRange(i);
707
Douglas Gregor3bb30002009-02-26 21:00:50 +0000708 unsigned NumHints = Info.getNumCodeModificationHints();
709 for (unsigned idx = 0; idx < NumHints; ++idx) {
710 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
711 if (Hint.RemoveRange.isValid()) {
712 assert(NumRanges < 20 && "Out of space");
713 Ranges[NumRanges++] = Hint.RemoveRange;
714 }
715 }
716
717 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
718 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000719 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000720 WordWrapped? WordWrapIndentation : 0,
721 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000722 }
Chris Lattner92a33532008-11-19 06:56:25 +0000723
724 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000725}