blob: 95171604d382449c551c32479d70c5588af23c92 [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.
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000171 if (CaretStart && !StartIsFixed) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000172 unsigned NewStart = CaretStart;
173
174 bool BadStart = false;
175 do {
176 // Skip over any whitespace we see here; we're looking for
177 // another bit of interesting text.
178 if (NewStart)
179 --NewStart;
180 while (NewStart && isspace(SourceLine[NewStart]))
181 --NewStart;
182
183 // Skip over this bit of "interesting" text.
184 while (NewStart && !isspace(SourceLine[NewStart])) {
185 if (isClosingDelimiter(SourceLine[NewStart]))
186 StartIsFixed = true;
187 --NewStart;
188 }
189
190 // Move up to the non-whitespace character we just saw.
191 if (!StartIsFixed &&
192 isspace(SourceLine[NewStart]) &&
193 !isspace(SourceLine[NewStart + 1]))
194 ++NewStart;
195
196 // Never go back past closing delimeters, because
197 // they're unlikely to be important (and they result in
198 // weird slices). Instead, move forward to the next
199 // non-whitespace character.
200 BadStart = false;
201 if (StartIsFixed) {
202 ++NewStart;
203 while (NewStart != CaretEnd && isspace(SourceLine[NewStart]))
204 ++NewStart;
205 } else if (NewStart) {
206 // There are some characters that always signal that we've
207 // found a bad stopping place, because they always occur in
208 // the middle of or at the end of an expression. In these
209 // cases, we either keep bringing in more "interesting" text
210 // to try to get to a somewhat-complete slice of the code.
211 BadStart = ispunct(SourceLine[NewStart]);
212 }
213 } while (BadStart);
214
215 // If we're still within our limit, update the starting
216 // position within the source/caret line.
217 if (CaretEnd - NewStart <= TargetColumns && !StartIsFixed) {
218 CaretStart = NewStart;
219 ExpandedRegion = true;
220 }
221 }
222
223 // Move the end of the interesting region right until we've
224 // pulled in something else interesting.
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000225 if (CaretEnd != SourceLength) {
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000226 unsigned NewEnd = CaretEnd;
227
228 // Skip over any whitespace we see here; we're looking for
229 // another bit of interesting text.
230 while (CaretEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
231 ++NewEnd;
232
233 // Skip over this bit of "interesting" text.
234 while (CaretEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
235 ++NewEnd;
236
237 if (NewEnd - CaretStart <= TargetColumns) {
238 CaretEnd = NewEnd;
239 ExpandedRegion = true;
240 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000241 }
Daniel Dunbar9cc1d782009-05-03 23:04:40 +0000242
243 if (!ExpandedRegion)
244 break;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000245 }
246
247 // [CaretStart, CaretEnd) is the slice we want. Update the various
248 // output lines to show only this slice, with two-space padding
249 // before the lines so that it looks nicer.
Douglas Gregor99bb2922009-05-03 04:12:51 +0000250 if (CaretEnd < SourceLine.size())
251 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregorc271ecb2009-05-03 15:24:25 +0000252 if (CaretEnd < CaretLine.size())
253 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000254 if (FixItInsertionLine.size() > CaretEnd)
255 FixItInsertionLine.erase(CaretEnd, std::string::npos);
256
257 if (CaretStart > 2) {
Douglas Gregor99bb2922009-05-03 04:12:51 +0000258 SourceLine.replace(0, CaretStart, " ...");
259 CaretLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000260 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor99bb2922009-05-03 04:12:51 +0000261 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000262 }
263}
264
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000265void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
Chris Lattner3272e922009-02-20 00:25:28 +0000266 SourceRange *Ranges,
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000267 unsigned NumRanges,
Douglas Gregor3bb30002009-02-26 21:00:50 +0000268 SourceManager &SM,
269 const CodeModificationHint *Hints,
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000270 unsigned NumHints,
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000271 unsigned AvoidColumn,
272 unsigned Columns) {
Chris Lattner37f9ad22009-02-17 08:44:50 +0000273 assert(!Loc.isInvalid() && "must have a valid source location here");
274
Chris Lattner3b29a182009-02-17 07:54:55 +0000275 // We always emit diagnostics about the instantiation points, not the spelling
276 // points. This more closely correlates to what the user writes.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000277 if (!Loc.isFileID()) {
Chris Lattner459da5d2009-02-18 18:50:45 +0000278 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000279 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, AvoidColumn,
280 Columns);
Chris Lattner37f9ad22009-02-17 08:44:50 +0000281
Chris Lattner3272e922009-02-20 00:25:28 +0000282 // Map the location through the macro.
Chris Lattner37f9ad22009-02-17 08:44:50 +0000283 Loc = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(Loc));
Chris Lattner3272e922009-02-20 00:25:28 +0000284
285 // Map the ranges.
286 for (unsigned i = 0; i != NumRanges; ++i) {
287 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
288 if (S.isMacroID())
289 S = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(S));
290 if (E.isMacroID())
291 E = SM.getInstantiationLoc(SM.getImmediateSpellingLoc(E));
292 Ranges[i] = SourceRange(S, E);
293 }
Chris Lattner37f9ad22009-02-17 08:44:50 +0000294
Chris Lattnerfd0739e2009-04-21 03:57:54 +0000295 if (ShowLocation) {
296 // Emit the file/line/column that this expansion came from.
297 OS << SM.getBufferName(Loc) << ':' << SM.getInstantiationLineNumber(Loc)
298 << ':';
299 if (ShowColumn)
300 OS << SM.getInstantiationColumnNumber(Loc) << ':';
301 OS << ' ';
302 }
303 OS << "note: instantiated from:\n";
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000304 AvoidColumn = 0;
Chris Lattner37f9ad22009-02-17 08:44:50 +0000305 }
Chris Lattner34e6c262009-02-17 07:51:53 +0000306
307 // Decompose the location into a FID/Offset pair.
308 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
309 FileID FID = LocInfo.first;
310 unsigned FileOffset = LocInfo.second;
311
312 // Get information about the buffer it points into.
313 std::pair<const char*, const char*> BufferInfo = SM.getBufferData(FID);
314 const char *BufStart = BufferInfo.first;
Chris Lattner34e6c262009-02-17 07:51:53 +0000315
316 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000317
318 // Rewind from the current position to the start of the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000319 const char *TokPtr = BufStart+FileOffset;
320 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
321
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000322
323 // Compute the line end. Scan forward from the error position to the end of
324 // the line.
Chris Lattner34e6c262009-02-17 07:51:53 +0000325 const char *LineEnd = TokPtr;
Chris Lattnerd9e72412009-03-08 08:11:22 +0000326 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000327 ++LineEnd;
328
329 // Copy the line of code into an std::string for ease of manipulation.
330 std::string SourceLine(LineStart, LineEnd);
331
332 // Create a line for the caret that is filled with spaces that is the same
333 // length as the line of source code.
334 std::string CaretLine(LineEnd-LineStart, ' ');
335
336 // Highlight all of the characters covered by Ranges with ~ characters.
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000337 if (NumRanges) {
Chris Lattner34e6c262009-02-17 07:51:53 +0000338 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
339
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000340 for (unsigned i = 0, e = NumRanges; i != e; ++i)
341 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
Chris Lattner34e6c262009-02-17 07:51:53 +0000342 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000343
344 // Next, insert the caret itself.
345 if (ColNo-1 < CaretLine.size())
346 CaretLine[ColNo-1] = '^';
347 else
348 CaretLine.push_back('^');
349
350 // Scan the source line, looking for tabs. If we find any, manually expand
351 // them to 8 characters and update the CaretLine to match.
352 for (unsigned i = 0; i != SourceLine.size(); ++i) {
353 if (SourceLine[i] != '\t') continue;
354
355 // Replace this tab with at least one space.
356 SourceLine[i] = ' ';
357
358 // Compute the number of spaces we need to insert.
359 unsigned NumSpaces = ((i+8)&~7) - (i+1);
360 assert(NumSpaces < 8 && "Invalid computation of space amt");
361
362 // Insert spaces into the SourceLine.
363 SourceLine.insert(i+1, NumSpaces, ' ');
364
365 // Insert spaces or ~'s into CaretLine.
366 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
367 }
368
Chris Lattner404ba8e2009-04-28 22:33:16 +0000369 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
370 // produce easily machine parsable output. Add a space before the source line
371 // and the caret to make it trivial to tell the main diagnostic line from what
372 // the user is intended to see.
373 if (PrintRangeInfo) {
374 SourceLine = ' ' + SourceLine;
375 CaretLine = ' ' + CaretLine;
376 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000377
378 std::string FixItInsertionLine;
Chris Lattner041bd732009-04-19 07:44:08 +0000379 if (NumHints && PrintFixItInfo) {
Chris Lattner041bd732009-04-19 07:44:08 +0000380 for (const CodeModificationHint *Hint = Hints, *LastHint = Hints + NumHints;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000381 Hint != LastHint; ++Hint) {
382 if (Hint->InsertionLoc.isValid()) {
383 // We have an insertion hint. Determine whether the inserted
384 // code is on the same line as the caret.
385 std::pair<FileID, unsigned> HintLocInfo
Chris Lattner9ccffa72009-03-02 20:58:48 +0000386 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000387 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
388 SM.getLineNumber(FID, FileOffset)) {
389 // Insert the new code into the line just below the code
390 // that the user wrote.
391 unsigned HintColNo
392 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
393 unsigned LastColumnModified
394 = HintColNo - 1 + Hint->CodeToInsert.size();
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000395 if (LastColumnModified > FixItInsertionLine.size())
396 FixItInsertionLine.resize(LastColumnModified, ' ');
Douglas Gregor3bb30002009-02-26 21:00:50 +0000397 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000398 FixItInsertionLine.begin() + HintColNo - 1);
Douglas Gregorb5579aa2009-05-03 04:33:32 +0000399 } else {
400 FixItInsertionLine.clear();
401 break;
Douglas Gregor3bb30002009-02-26 21:00:50 +0000402 }
403 }
404 }
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000405 }
Douglas Gregor3bb30002009-02-26 21:00:50 +0000406
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000407 // If the source line is too long for our terminal, select only the
408 // "interesting" source region within that line.
409 if (Columns && SourceLine.size() > Columns)
410 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
411 Columns);
412
413 // AvoidColumn tells us which column we should avoid when printing
414 // the source line. If the source line would start at or near that
415 // column, add another line of whitespace before printing the source
416 // line. Otherwise, the source line and the diagnostic text can get
417 // jumbled together.
418 unsigned StartCol = 0;
419 for (unsigned N = SourceLine.size(); StartCol != N; ++StartCol)
420 if (!isspace(SourceLine[StartCol]))
421 break;
422
423 if (StartCol != SourceLine.size() &&
424 abs((int)StartCol - (int)AvoidColumn) <= 2)
425 OS << '\n';
426
427 // Finally, remove any blank spaces from the end of CaretLine.
428 while (CaretLine[CaretLine.size()-1] == ' ')
429 CaretLine.erase(CaretLine.end()-1);
430
431 // Emit what we have computed.
432 OS << SourceLine << '\n';
433 OS << CaretLine << '\n';
434
435 if (!FixItInsertionLine.empty()) {
436 if (PrintRangeInfo)
437 OS << ' ';
438 OS << FixItInsertionLine << '\n';
Douglas Gregor3bb30002009-02-26 21:00:50 +0000439 }
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000440}
441
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000442/// \brief Skip over whitespace in the string, starting at the given
443/// index.
444///
445/// \returns The index of the first non-whitespace character that is
446/// greater than or equal to Idx or, if no such character exists,
447/// returns the end of the string.
448static unsigned skipWhitespace(unsigned Idx,
449 const llvm::SmallVectorImpl<char> &Str,
450 unsigned Length) {
451 while (Idx < Length && isspace(Str[Idx]))
452 ++Idx;
453 return Idx;
454}
455
456/// \brief If the given character is the start of some kind of
457/// balanced punctuation (e.g., quotes or parentheses), return the
458/// character that will terminate the punctuation.
459///
460/// \returns The ending punctuation character, if any, or the NULL
461/// character if the input character does not start any punctuation.
462static inline char findMatchingPunctuation(char c) {
463 switch (c) {
464 case '\'': return '\'';
465 case '`': return '\'';
466 case '"': return '"';
467 case '(': return ')';
468 case '[': return ']';
469 case '{': return '}';
470 default: break;
471 }
472
473 return 0;
474}
475
476/// \brief Find the end of the word starting at the given offset
477/// within a string.
478///
479/// \returns the index pointing one character past the end of the
480/// word.
481unsigned findEndOfWord(unsigned Start,
482 const llvm::SmallVectorImpl<char> &Str,
483 unsigned Length, unsigned Column,
484 unsigned Columns) {
485 unsigned End = Start + 1;
486
487 // Determine if the start of the string is actually opening
488 // punctuation, e.g., a quote or parentheses.
489 char EndPunct = findMatchingPunctuation(Str[Start]);
490 if (!EndPunct) {
491 // This is a normal word. Just find the first space character.
492 while (End < Length && !isspace(Str[End]))
493 ++End;
494 return End;
495 }
496
497 // We have the start of a balanced punctuation sequence (quotes,
498 // parentheses, etc.). Determine the full sequence is.
499 llvm::SmallVector<char, 16> PunctuationEndStack;
500 PunctuationEndStack.push_back(EndPunct);
501 while (End < Length && !PunctuationEndStack.empty()) {
502 if (Str[End] == PunctuationEndStack.back())
503 PunctuationEndStack.pop_back();
504 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
505 PunctuationEndStack.push_back(SubEndPunct);
506
507 ++End;
508 }
509
510 // Find the first space character after the punctuation ended.
511 while (End < Length && !isspace(Str[End]))
512 ++End;
513
514 unsigned PunctWordLength = End - Start;
515 if (// If the word fits on this line
516 Column + PunctWordLength <= Columns ||
517 // ... or the word is "short enough" to take up the next line
518 // without too much ugly white space
519 PunctWordLength < Columns/3)
520 return End; // Take the whole thing as a single "word".
521
522 // The whole quoted/parenthesized string is too long to print as a
523 // single "word". Instead, find the "word" that starts just after
524 // the punctuation and use that end-point instead. This will recurse
525 // until it finds something small enough to consider a word.
526 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
527}
528
529/// \brief Print the given string to a stream, word-wrapping it to
530/// some number of columns in the process.
531///
532/// \brief OS the stream to which the word-wrapping string will be
533/// emitted.
534///
535/// \brief Str the string to word-wrap and output.
536///
537/// \brief Columns the number of columns to word-wrap to.
538///
539/// \brief Column the column number at which the first character of \p
540/// Str will be printed. This will be non-zero when part of the first
541/// line has already been printed.
542///
543/// \brief Indentation the number of spaces to indent any lines beyond
544/// the first line.
545///
546/// \returns true if word-wrapping was required, or false if the
547/// string fit on the first line.
548static bool PrintWordWrapped(llvm::raw_ostream &OS,
549 const llvm::SmallVectorImpl<char> &Str,
550 unsigned Columns,
551 unsigned Column = 0,
552 unsigned Indentation = WordWrapIndentation) {
553 unsigned Length = Str.size();
554
555 // If there is a newline in this message somewhere, find that
556 // newline and split the message into the part before the newline
557 // (which will be word-wrapped) and the part from the newline one
558 // (which will be emitted unchanged).
559 for (unsigned I = 0; I != Length; ++I)
560 if (Str[I] == '\n') {
561 Length = I;
562 break;
563 }
564
565 // The string used to indent each line.
566 llvm::SmallString<16> IndentStr;
567 IndentStr.assign(Indentation, ' ');
568 bool Wrapped = false;
569 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
570 WordStart = WordEnd) {
571 // Find the beginning of the next word.
572 WordStart = skipWhitespace(WordStart, Str, Length);
573 if (WordStart == Length)
574 break;
575
576 // Find the end of this word.
577 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
578
579 // Does this word fit on the current line?
580 unsigned WordLength = WordEnd - WordStart;
581 if (Column + WordLength < Columns) {
582 // This word fits on the current line; print it there.
583 if (WordStart) {
584 OS << ' ';
585 Column += 1;
586 }
587 OS.write(&Str[WordStart], WordLength);
588 Column += WordLength;
589 continue;
590 }
591
592 // This word does not fit on the current line, so wrap to the next
593 // line.
Douglas Gregor3dd11e82009-05-03 03:52:38 +0000594 OS << '\n';
595 OS.write(&IndentStr[0], Indentation);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000596 OS.write(&Str[WordStart], WordLength);
597 Column = Indentation + WordLength;
598 Wrapped = true;
599 }
600
601 if (Length == Str.size())
602 return Wrapped; // We're done.
603
604 // There is a newline in the message, followed by something that
605 // will not be word-wrapped. Print that.
606 OS.write(&Str[Length], Str.size() - Length);
607 return true;
608}
Chris Lattnerc1303fb2009-02-17 07:38:37 +0000609
Chris Lattner6948ae62008-11-18 07:04:44 +0000610void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
611 const DiagnosticInfo &Info) {
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000612 // Keeps track of the the starting position of the location
613 // information (e.g., "foo.c:10:4:") that precedes the error
614 // message. We use this information to determine how long the
615 // file+line+column number prefix is.
616 uint64_t StartOfLocationInfo = OS.tell();
617
Chris Lattner836774b2009-01-27 07:57:44 +0000618 // If the location is specified, print out a file/line/col and include trace
619 // if enabled.
620 if (Info.getLocation().isValid()) {
Ted Kremenekdd62ea62009-01-28 20:47:47 +0000621 const SourceManager &SM = Info.getLocation().getManager();
Chris Lattner836774b2009-01-27 07:57:44 +0000622 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
623 unsigned LineNo = PLoc.getLine();
Chris Lattner4b009652007-07-25 00:24:17 +0000624
625 // First, if this diagnostic is not in the main file, print out the
626 // "included from" lines.
Chris Lattner836774b2009-01-27 07:57:44 +0000627 if (LastWarningLoc != PLoc.getIncludeLoc()) {
628 LastWarningLoc = PLoc.getIncludeLoc();
629 PrintIncludeStack(LastWarningLoc, SM);
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000630 StartOfLocationInfo = OS.tell();
Chris Lattner4b009652007-07-25 00:24:17 +0000631 }
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000632
Chris Lattner836774b2009-01-27 07:57:44 +0000633 // Compute the column number.
Chris Lattner68c1e192009-01-30 17:41:53 +0000634 if (ShowLocation) {
635 OS << PLoc.getFilename() << ':' << LineNo << ':';
Chris Lattnerf0b28562009-02-17 07:34:34 +0000636 if (ShowColumn)
637 if (unsigned ColNo = PLoc.getColumn())
638 OS << ColNo << ':';
Chris Lattner695a4f52009-03-13 01:08:23 +0000639
640 if (PrintRangeInfo && Info.getNumRanges()) {
641 FileID CaretFileID =
642 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
643 bool PrintedRange = false;
644
645 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
Chris Lattner94780632009-04-19 22:24:10 +0000646 // Ignore invalid ranges.
647 if (!Info.getRange(i).isValid()) continue;
648
Chris Lattner695a4f52009-03-13 01:08:23 +0000649 SourceLocation B = Info.getRange(i).getBegin();
650 SourceLocation E = Info.getRange(i).getEnd();
651 std::pair<FileID, unsigned> BInfo=SM.getDecomposedInstantiationLoc(B);
652
653 E = SM.getInstantiationLoc(E);
654 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
655
656 // If the start or end of the range is in another file, just discard
657 // it.
658 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
659 continue;
660
661 // Add in the length of the token, so that we cover multi-char tokens.
Chris Lattnere1be6022009-04-14 23:22:57 +0000662 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
Chris Lattner695a4f52009-03-13 01:08:23 +0000663
664 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
665 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
666 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
667 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
668 PrintedRange = true;
669 }
670
671 if (PrintedRange)
672 OS << ':';
673 }
Chris Lattner68c1e192009-01-30 17:41:53 +0000674 OS << ' ';
675 }
Chris Lattner4b009652007-07-25 00:24:17 +0000676 }
677
678 switch (Level) {
Chris Lattner95cb5502009-02-06 03:57:44 +0000679 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
Nate Begeman01d74272008-04-17 18:06:57 +0000680 case Diagnostic::Note: OS << "note: "; break;
681 case Diagnostic::Warning: OS << "warning: "; break;
682 case Diagnostic::Error: OS << "error: "; break;
Chris Lattner95cb5502009-02-06 03:57:44 +0000683 case Diagnostic::Fatal: OS << "fatal error: "; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000684 }
685
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000686 llvm::SmallString<100> OutStr;
687 Info.FormatDiagnostic(OutStr);
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000688
689 if (PrintDiagnosticOption)
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000690 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
691 OutStr += " [-W";
692 OutStr += Opt;
693 OutStr += ']';
694 }
Chris Lattnera96ec3b2009-04-16 05:44:38 +0000695
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000696 bool WordWrapped = false;
697 if (MessageLength) {
698 // We will be word-wrapping the error message, so compute the
699 // column number where we currently are (after printing the
700 // location information).
701 unsigned Column = OS.tell() - StartOfLocationInfo;
702 WordWrapped = PrintWordWrapped(OS, OutStr, MessageLength, Column);
703 } else {
704 OS.write(OutStr.begin(), OutStr.size());
705 }
Chris Lattnerbe8e5a42008-11-19 06:51:40 +0000706 OS << '\n';
Chris Lattner4b009652007-07-25 00:24:17 +0000707
Douglas Gregor56d25a72009-03-10 20:44:00 +0000708 // If caret diagnostics are enabled and we have location, we want to
709 // emit the caret. However, we only do this if the location moved
710 // from the last diagnostic, if the last diagnostic was a note that
711 // was part of a different warning or error diagnostic, or if the
712 // diagnostic has ranges. We don't want to emit the same caret
713 // multiple times if one loc has multiple diagnostics.
Chris Lattner836774b2009-01-27 07:57:44 +0000714 if (CaretDiagnostics && Info.getLocation().isValid() &&
Douglas Gregor3bb30002009-02-26 21:00:50 +0000715 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
Douglas Gregor56d25a72009-03-10 20:44:00 +0000716 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
Douglas Gregor3bb30002009-02-26 21:00:50 +0000717 Info.getNumCodeModificationHints())) {
Steve Naroffb268d2a2008-02-08 22:06:17 +0000718 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Chris Lattner836774b2009-01-27 07:57:44 +0000719 LastLoc = Info.getLocation();
Douglas Gregor56d25a72009-03-10 20:44:00 +0000720 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
Chris Lattner836774b2009-01-27 07:57:44 +0000721
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000722 // Get the ranges into a local array we can hack on.
Douglas Gregor3bb30002009-02-26 21:00:50 +0000723 SourceRange Ranges[20];
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000724 unsigned NumRanges = Info.getNumRanges();
Douglas Gregor3bb30002009-02-26 21:00:50 +0000725 assert(NumRanges < 20 && "Out of space");
Chris Lattnerec52b7d2009-02-20 00:18:51 +0000726 for (unsigned i = 0; i != NumRanges; ++i)
727 Ranges[i] = Info.getRange(i);
728
Douglas Gregor3bb30002009-02-26 21:00:50 +0000729 unsigned NumHints = Info.getNumCodeModificationHints();
730 for (unsigned idx = 0; idx < NumHints; ++idx) {
731 const CodeModificationHint &Hint = Info.getCodeModificationHint(idx);
732 if (Hint.RemoveRange.isValid()) {
733 assert(NumRanges < 20 && "Out of space");
734 Ranges[NumRanges++] = Hint.RemoveRange;
735 }
736 }
737
738 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
739 Info.getCodeModificationHints(),
Douglas Gregora4eb3e72009-05-01 21:53:04 +0000740 Info.getNumCodeModificationHints(),
Douglas Gregorf2ab4fb2009-05-01 23:32:58 +0000741 WordWrapped? WordWrapIndentation : 0,
742 MessageLength);
Chris Lattner4b009652007-07-25 00:24:17 +0000743 }
Chris Lattner92a33532008-11-19 06:56:25 +0000744
745 OS.flush();
Chris Lattner4b009652007-07-25 00:24:17 +0000746}