Deleted Added
sdiff udiff text old ( 207632 ) new ( 208600 )
full compact
1//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/TextDiagnosticPrinter.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Frontend/DiagnosticOptions.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/Support/MemoryBuffer.h"
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/ADT/SmallString.h"
21#include <algorithm>
22using namespace clang;
23
24static const enum llvm::raw_ostream::Colors noteColor =
25 llvm::raw_ostream::BLACK;
26static const enum llvm::raw_ostream::Colors fixitColor =
27 llvm::raw_ostream::GREEN;
28static const enum llvm::raw_ostream::Colors caretColor =
29 llvm::raw_ostream::GREEN;
30static const enum llvm::raw_ostream::Colors warningColor =
31 llvm::raw_ostream::MAGENTA;
32static const enum llvm::raw_ostream::Colors errorColor = llvm::raw_ostream::RED;
33static const enum llvm::raw_ostream::Colors fatalColor = llvm::raw_ostream::RED;
34// Used for changing only the bold attribute.
35static const enum llvm::raw_ostream::Colors savedColor =
36 llvm::raw_ostream::SAVEDCOLOR;
37
38/// \brief Number of spaces to indent when word-wrapping.
39const unsigned WordWrapIndentation = 6;
40
41TextDiagnosticPrinter::TextDiagnosticPrinter(llvm::raw_ostream &os,
42 const DiagnosticOptions &diags,
43 bool _OwnsOutputStream)
44 : OS(os), LangOpts(0), DiagOpts(&diags),
45 LastCaretDiagnosticWasNote(0),
46 OwnsOutputStream(_OwnsOutputStream) {
47}
48
49TextDiagnosticPrinter::~TextDiagnosticPrinter() {
50 if (OwnsOutputStream)
51 delete &OS;
52}
53
54void TextDiagnosticPrinter::
55PrintIncludeStack(SourceLocation Loc, const SourceManager &SM) {
56 if (Loc.isInvalid()) return;
57
58 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
59
60 // Print out the other include frames first.
61 PrintIncludeStack(PLoc.getIncludeLoc(), SM);
62
63 if (DiagOpts->ShowLocation)
64 OS << "In file included from " << PLoc.getFilename()
65 << ':' << PLoc.getLine() << ":\n";
66 else
67 OS << "In included file:\n";
68}
69
70/// HighlightRange - Given a SourceRange and a line number, highlight (with ~'s)
71/// any characters in LineNo that intersect the SourceRange.
72void TextDiagnosticPrinter::HighlightRange(const SourceRange &R,
73 const SourceManager &SM,
74 unsigned LineNo, FileID FID,
75 std::string &CaretLine,
76 const std::string &SourceLine) {
77 assert(CaretLine.size() == SourceLine.size() &&
78 "Expect a correspondence between source and caret line!");
79 if (!R.isValid()) return;
80
81 SourceLocation Begin = SM.getInstantiationLoc(R.getBegin());
82 SourceLocation End = SM.getInstantiationLoc(R.getEnd());
83
84 // If the End location and the start location are the same and are a macro
85 // location, then the range was something that came from a macro expansion
86 // or _Pragma. If this is an object-like macro, the best we can do is to
87 // highlight the range. If this is a function-like macro, we'd also like to
88 // highlight the arguments.
89 if (Begin == End && R.getEnd().isMacroID())
90 End = SM.getInstantiationRange(R.getEnd()).second;
91
92 unsigned StartLineNo = SM.getInstantiationLineNumber(Begin);
93 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
94 return; // No intersection.
95
96 unsigned EndLineNo = SM.getInstantiationLineNumber(End);
97 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
98 return; // No intersection.
99
100 // Compute the column number of the start.
101 unsigned StartColNo = 0;
102 if (StartLineNo == LineNo) {
103 StartColNo = SM.getInstantiationColumnNumber(Begin);
104 if (StartColNo) --StartColNo; // Zero base the col #.
105 }
106
107 // Compute the column number of the end.
108 unsigned EndColNo = CaretLine.size();
109 if (EndLineNo == LineNo) {
110 EndColNo = SM.getInstantiationColumnNumber(End);
111 if (EndColNo) {
112 --EndColNo; // Zero base the col #.
113
114 // Add in the length of the token, so that we cover multi-char tokens.
115 EndColNo += Lexer::MeasureTokenLength(End, SM, *LangOpts);
116 } else {
117 EndColNo = CaretLine.size();
118 }
119 }
120
121 assert(StartColNo <= EndColNo && "Invalid range!");
122
123 // Pick the first non-whitespace column.
124 while (StartColNo < SourceLine.size() &&
125 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
126 ++StartColNo;
127
128 // Pick the last non-whitespace column.
129 if (EndColNo > SourceLine.size())
130 EndColNo = SourceLine.size();
131 while (EndColNo-1 &&
132 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
133 --EndColNo;
134
135 // If the start/end passed each other, then we are trying to highlight a range
136 // that just exists in whitespace, which must be some sort of other bug.
137 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
138
139 // Fill the range with ~'s.
140 for (unsigned i = StartColNo; i < EndColNo; ++i)
141 CaretLine[i] = '~';
142}
143
144/// \brief When the source code line we want to print is too long for
145/// the terminal, select the "interesting" region.
146static void SelectInterestingSourceRegion(std::string &SourceLine,
147 std::string &CaretLine,
148 std::string &FixItInsertionLine,
149 unsigned EndOfCaretToken,
150 unsigned Columns) {
151 unsigned MaxSize = std::max(SourceLine.size(),
152 std::max(CaretLine.size(),
153 FixItInsertionLine.size()));
154 if (MaxSize > SourceLine.size())
155 SourceLine.resize(MaxSize, ' ');
156 if (MaxSize > CaretLine.size())
157 CaretLine.resize(MaxSize, ' ');
158 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
159 FixItInsertionLine.resize(MaxSize, ' ');
160
161 // Find the slice that we need to display the full caret line
162 // correctly.
163 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
164 for (; CaretStart != CaretEnd; ++CaretStart)
165 if (!isspace(CaretLine[CaretStart]))
166 break;
167
168 for (; CaretEnd != CaretStart; --CaretEnd)
169 if (!isspace(CaretLine[CaretEnd - 1]))
170 break;
171
172 // Make sure we don't chop the string shorter than the caret token
173 // itself.
174 if (CaretEnd < EndOfCaretToken)
175 CaretEnd = EndOfCaretToken;
176
177 // If we have a fix-it line, make sure the slice includes all of the
178 // fix-it information.
179 if (!FixItInsertionLine.empty()) {
180 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
181 for (; FixItStart != FixItEnd; ++FixItStart)
182 if (!isspace(FixItInsertionLine[FixItStart]))
183 break;
184
185 for (; FixItEnd != FixItStart; --FixItEnd)
186 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
187 break;
188
189 if (FixItStart < CaretStart)
190 CaretStart = FixItStart;
191 if (FixItEnd > CaretEnd)
192 CaretEnd = FixItEnd;
193 }
194
195 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
196 // parts of the caret line. While this slice is smaller than the
197 // number of columns we have, try to grow the slice to encompass
198 // more context.
199
200 // If the end of the interesting region comes before we run out of
201 // space in the terminal, start at the beginning of the line.
202 if (Columns > 3 && CaretEnd < Columns - 3)
203 CaretStart = 0;
204
205 unsigned TargetColumns = Columns;
206 if (TargetColumns > 8)
207 TargetColumns -= 8; // Give us extra room for the ellipses.
208 unsigned SourceLength = SourceLine.size();
209 while ((CaretEnd - CaretStart) < TargetColumns) {
210 bool ExpandedRegion = false;
211 // Move the start of the interesting region left until we've
212 // pulled in something else interesting.
213 if (CaretStart == 1)
214 CaretStart = 0;
215 else if (CaretStart > 1) {
216 unsigned NewStart = CaretStart - 1;
217
218 // Skip over any whitespace we see here; we're looking for
219 // another bit of interesting text.
220 while (NewStart && isspace(SourceLine[NewStart]))
221 --NewStart;
222
223 // Skip over this bit of "interesting" text.
224 while (NewStart && !isspace(SourceLine[NewStart]))
225 --NewStart;
226
227 // Move up to the non-whitespace character we just saw.
228 if (NewStart)
229 ++NewStart;
230
231 // If we're still within our limit, update the starting
232 // position within the source/caret line.
233 if (CaretEnd - NewStart <= TargetColumns) {
234 CaretStart = NewStart;
235 ExpandedRegion = true;
236 }
237 }
238
239 // Move the end of the interesting region right until we've
240 // pulled in something else interesting.
241 if (CaretEnd != SourceLength) {
242 assert(CaretEnd < SourceLength && "Unexpected caret position!");
243 unsigned NewEnd = CaretEnd;
244
245 // Skip over any whitespace we see here; we're looking for
246 // another bit of interesting text.
247 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
248 ++NewEnd;
249
250 // Skip over this bit of "interesting" text.
251 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
252 ++NewEnd;
253
254 if (NewEnd - CaretStart <= TargetColumns) {
255 CaretEnd = NewEnd;
256 ExpandedRegion = true;
257 }
258 }
259
260 if (!ExpandedRegion)
261 break;
262 }
263
264 // [CaretStart, CaretEnd) is the slice we want. Update the various
265 // output lines to show only this slice, with two-space padding
266 // before the lines so that it looks nicer.
267 if (CaretEnd < SourceLine.size())
268 SourceLine.replace(CaretEnd, std::string::npos, "...");
269 if (CaretEnd < CaretLine.size())
270 CaretLine.erase(CaretEnd, std::string::npos);
271 if (FixItInsertionLine.size() > CaretEnd)
272 FixItInsertionLine.erase(CaretEnd, std::string::npos);
273
274 if (CaretStart > 2) {
275 SourceLine.replace(0, CaretStart, " ...");
276 CaretLine.replace(0, CaretStart, " ");
277 if (FixItInsertionLine.size() >= CaretStart)
278 FixItInsertionLine.replace(0, CaretStart, " ");
279 }
280}
281
282void TextDiagnosticPrinter::EmitCaretDiagnostic(SourceLocation Loc,
283 SourceRange *Ranges,
284 unsigned NumRanges,
285 const SourceManager &SM,
286 const FixItHint *Hints,
287 unsigned NumHints,
288 unsigned Columns,
289 unsigned OnMacroInst,
290 unsigned MacroSkipStart,
291 unsigned MacroSkipEnd) {
292 assert(LangOpts && "Unexpected diagnostic outside source file processing");
293 assert(!Loc.isInvalid() && "must have a valid source location here");
294
295 // If this is a macro ID, first emit information about where this was
296 // instantiated (recursively) then emit information about where the token was
297 // spelled from.
298 if (!Loc.isFileID()) {
299 // Whether to suppress printing this macro instantiation.
300 bool Suppressed
301 = OnMacroInst >= MacroSkipStart && OnMacroInst < MacroSkipEnd;
302
303
304 SourceLocation OneLevelUp = SM.getImmediateInstantiationRange(Loc).first;
305 // FIXME: Map ranges?
306 EmitCaretDiagnostic(OneLevelUp, Ranges, NumRanges, SM, 0, 0, Columns,
307 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
308
309 // Map the location.
310 Loc = SM.getImmediateSpellingLoc(Loc);
311
312 // Map the ranges.
313 for (unsigned i = 0; i != NumRanges; ++i) {
314 SourceLocation S = Ranges[i].getBegin(), E = Ranges[i].getEnd();
315 if (S.isMacroID()) S = SM.getImmediateSpellingLoc(S);
316 if (E.isMacroID()) E = SM.getImmediateSpellingLoc(E);
317 Ranges[i] = SourceRange(S, E);
318 }
319
320 if (!Suppressed) {
321 // Get the pretty name, according to #line directives etc.
322 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
323
324 // If this diagnostic is not in the main file, print out the
325 // "included from" lines.
326 if (LastWarningLoc != PLoc.getIncludeLoc()) {
327 LastWarningLoc = PLoc.getIncludeLoc();
328 PrintIncludeStack(LastWarningLoc, SM);
329 }
330
331 if (DiagOpts->ShowLocation) {
332 // Emit the file/line/column that this expansion came from.
333 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
334 if (DiagOpts->ShowColumn)
335 OS << PLoc.getColumn() << ':';
336 OS << ' ';
337 }
338 OS << "note: instantiated from:\n";
339
340 EmitCaretDiagnostic(Loc, Ranges, NumRanges, SM, Hints, NumHints, Columns,
341 OnMacroInst + 1, MacroSkipStart, MacroSkipEnd);
342 return;
343 }
344
345 if (OnMacroInst == MacroSkipStart) {
346 // Tell the user that we've skipped contexts.
347 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
348 << " contexts in backtrace; use -fmacro-backtrace-limit=0 to see "
349 "all)\n";
350 }
351
352 return;
353 }
354
355 // Decompose the location into a FID/Offset pair.
356 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
357 FileID FID = LocInfo.first;
358 unsigned FileOffset = LocInfo.second;
359
360 // Get information about the buffer it points into.
361 bool Invalid = false;
362 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
363 if (Invalid)
364 return;
365
366 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
367 unsigned CaretEndColNo
368 = ColNo + Lexer::MeasureTokenLength(Loc, SM, *LangOpts);
369
370 // Rewind from the current position to the start of the line.
371 const char *TokPtr = BufStart+FileOffset;
372 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
373
374
375 // Compute the line end. Scan forward from the error position to the end of
376 // the line.
377 const char *LineEnd = TokPtr;
378 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
379 ++LineEnd;
380
381 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
382 // the source line length as currently being computed. See
383 // test/Misc/message-length.c.
384 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
385
386 // Copy the line of code into an std::string for ease of manipulation.
387 std::string SourceLine(LineStart, LineEnd);
388
389 // Create a line for the caret that is filled with spaces that is the same
390 // length as the line of source code.
391 std::string CaretLine(LineEnd-LineStart, ' ');
392
393 // Highlight all of the characters covered by Ranges with ~ characters.
394 if (NumRanges) {
395 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
396
397 for (unsigned i = 0, e = NumRanges; i != e; ++i)
398 HighlightRange(Ranges[i], SM, LineNo, FID, CaretLine, SourceLine);
399 }
400
401 // Next, insert the caret itself.
402 if (ColNo-1 < CaretLine.size())
403 CaretLine[ColNo-1] = '^';
404 else
405 CaretLine.push_back('^');
406
407 // Scan the source line, looking for tabs. If we find any, manually expand
408 // them to spaces and update the CaretLine to match.
409 for (unsigned i = 0; i != SourceLine.size(); ++i) {
410 if (SourceLine[i] != '\t') continue;
411
412 // Replace this tab with at least one space.
413 SourceLine[i] = ' ';
414
415 // Compute the number of spaces we need to insert.
416 unsigned TabStop = DiagOpts->TabStop;
417 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
418 "Invalid -ftabstop value");
419 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
420 assert(NumSpaces < TabStop && "Invalid computation of space amt");
421
422 // Insert spaces into the SourceLine.
423 SourceLine.insert(i+1, NumSpaces, ' ');
424
425 // Insert spaces or ~'s into CaretLine.
426 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
427 }
428
429 // If we are in -fdiagnostics-print-source-range-info mode, we are trying to
430 // produce easily machine parsable output. Add a space before the source line
431 // and the caret to make it trivial to tell the main diagnostic line from what
432 // the user is intended to see.
433 if (DiagOpts->ShowSourceRanges) {
434 SourceLine = ' ' + SourceLine;
435 CaretLine = ' ' + CaretLine;
436 }
437
438 std::string FixItInsertionLine;
439 if (NumHints && DiagOpts->ShowFixits) {
440 for (const FixItHint *Hint = Hints, *LastHint = Hints + NumHints;
441 Hint != LastHint; ++Hint) {
442 if (Hint->InsertionLoc.isValid()) {
443 // We have an insertion hint. Determine whether the inserted
444 // code is on the same line as the caret.
445 std::pair<FileID, unsigned> HintLocInfo
446 = SM.getDecomposedInstantiationLoc(Hint->InsertionLoc);
447 if (SM.getLineNumber(HintLocInfo.first, HintLocInfo.second) ==
448 SM.getLineNumber(FID, FileOffset)) {
449 // Insert the new code into the line just below the code
450 // that the user wrote.
451 unsigned HintColNo
452 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
453 unsigned LastColumnModified
454 = HintColNo - 1 + Hint->CodeToInsert.size();
455 if (LastColumnModified > FixItInsertionLine.size())
456 FixItInsertionLine.resize(LastColumnModified, ' ');
457 std::copy(Hint->CodeToInsert.begin(), Hint->CodeToInsert.end(),
458 FixItInsertionLine.begin() + HintColNo - 1);
459 } else {
460 FixItInsertionLine.clear();
461 break;
462 }
463 }
464 }
465 // Now that we have the entire fixit line, expand the tabs in it.
466 // Since we don't want to insert spaces in the middle of a word,
467 // find each word and the column it should line up with and insert
468 // spaces until they match.
469 if (!FixItInsertionLine.empty()) {
470 unsigned FixItPos = 0;
471 unsigned LinePos = 0;
472 unsigned TabExpandedCol = 0;
473 unsigned LineLength = LineEnd - LineStart;
474
475 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
476 // Find the next word in the FixIt line.
477 while (FixItPos < FixItInsertionLine.size() &&
478 FixItInsertionLine[FixItPos] == ' ')
479 ++FixItPos;
480 unsigned CharDistance = FixItPos - TabExpandedCol;
481
482 // Walk forward in the source line, keeping track of
483 // the tab-expanded column.
484 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
485 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
486 ++TabExpandedCol;
487 else
488 TabExpandedCol =
489 (TabExpandedCol/DiagOpts->TabStop + 1) * DiagOpts->TabStop;
490
491 // Adjust the fixit line to match this column.
492 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
493 FixItPos = TabExpandedCol;
494
495 // Walk to the end of the word.
496 while (FixItPos < FixItInsertionLine.size() &&
497 FixItInsertionLine[FixItPos] != ' ')
498 ++FixItPos;
499 }
500 }
501 }
502
503 // If the source line is too long for our terminal, select only the
504 // "interesting" source region within that line.
505 if (Columns && SourceLine.size() > Columns)
506 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
507 CaretEndColNo, Columns);
508
509 // Finally, remove any blank spaces from the end of CaretLine.
510 while (CaretLine[CaretLine.size()-1] == ' ')
511 CaretLine.erase(CaretLine.end()-1);
512
513 // Emit what we have computed.
514 OS << SourceLine << '\n';
515
516 if (DiagOpts->ShowColors)
517 OS.changeColor(caretColor, true);
518 OS << CaretLine << '\n';
519 if (DiagOpts->ShowColors)
520 OS.resetColor();
521
522 if (!FixItInsertionLine.empty()) {
523 if (DiagOpts->ShowColors)
524 // Print fixit line in color
525 OS.changeColor(fixitColor, false);
526 if (DiagOpts->ShowSourceRanges)
527 OS << ' ';
528 OS << FixItInsertionLine << '\n';
529 if (DiagOpts->ShowColors)
530 OS.resetColor();
531 }
532}
533
534/// \brief Skip over whitespace in the string, starting at the given
535/// index.
536///
537/// \returns The index of the first non-whitespace character that is
538/// greater than or equal to Idx or, if no such character exists,
539/// returns the end of the string.
540static unsigned skipWhitespace(unsigned Idx,
541 const llvm::SmallVectorImpl<char> &Str,
542 unsigned Length) {
543 while (Idx < Length && isspace(Str[Idx]))
544 ++Idx;
545 return Idx;
546}
547
548/// \brief If the given character is the start of some kind of
549/// balanced punctuation (e.g., quotes or parentheses), return the
550/// character that will terminate the punctuation.
551///
552/// \returns The ending punctuation character, if any, or the NULL
553/// character if the input character does not start any punctuation.
554static inline char findMatchingPunctuation(char c) {
555 switch (c) {
556 case '\'': return '\'';
557 case '`': return '\'';
558 case '"': return '"';
559 case '(': return ')';
560 case '[': return ']';
561 case '{': return '}';
562 default: break;
563 }
564
565 return 0;
566}
567
568/// \brief Find the end of the word starting at the given offset
569/// within a string.
570///
571/// \returns the index pointing one character past the end of the
572/// word.
573static unsigned findEndOfWord(unsigned Start,
574 const llvm::SmallVectorImpl<char> &Str,
575 unsigned Length, unsigned Column,
576 unsigned Columns) {
577 assert(Start < Str.size() && "Invalid start position!");
578 unsigned End = Start + 1;
579
580 // If we are already at the end of the string, take that as the word.
581 if (End == Str.size())
582 return End;
583
584 // Determine if the start of the string is actually opening
585 // punctuation, e.g., a quote or parentheses.
586 char EndPunct = findMatchingPunctuation(Str[Start]);
587 if (!EndPunct) {
588 // This is a normal word. Just find the first space character.
589 while (End < Length && !isspace(Str[End]))
590 ++End;
591 return End;
592 }
593
594 // We have the start of a balanced punctuation sequence (quotes,
595 // parentheses, etc.). Determine the full sequence is.
596 llvm::SmallString<16> PunctuationEndStack;
597 PunctuationEndStack.push_back(EndPunct);
598 while (End < Length && !PunctuationEndStack.empty()) {
599 if (Str[End] == PunctuationEndStack.back())
600 PunctuationEndStack.pop_back();
601 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
602 PunctuationEndStack.push_back(SubEndPunct);
603
604 ++End;
605 }
606
607 // Find the first space character after the punctuation ended.
608 while (End < Length && !isspace(Str[End]))
609 ++End;
610
611 unsigned PunctWordLength = End - Start;
612 if (// If the word fits on this line
613 Column + PunctWordLength <= Columns ||
614 // ... or the word is "short enough" to take up the next line
615 // without too much ugly white space
616 PunctWordLength < Columns/3)
617 return End; // Take the whole thing as a single "word".
618
619 // The whole quoted/parenthesized string is too long to print as a
620 // single "word". Instead, find the "word" that starts just after
621 // the punctuation and use that end-point instead. This will recurse
622 // until it finds something small enough to consider a word.
623 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
624}
625
626/// \brief Print the given string to a stream, word-wrapping it to
627/// some number of columns in the process.
628///
629/// \brief OS the stream to which the word-wrapping string will be
630/// emitted.
631///
632/// \brief Str the string to word-wrap and output.
633///
634/// \brief Columns the number of columns to word-wrap to.
635///
636/// \brief Column the column number at which the first character of \p
637/// Str will be printed. This will be non-zero when part of the first
638/// line has already been printed.
639///
640/// \brief Indentation the number of spaces to indent any lines beyond
641/// the first line.
642///
643/// \returns true if word-wrapping was required, or false if the
644/// string fit on the first line.
645static bool PrintWordWrapped(llvm::raw_ostream &OS,
646 const llvm::SmallVectorImpl<char> &Str,
647 unsigned Columns,
648 unsigned Column = 0,
649 unsigned Indentation = WordWrapIndentation) {
650 unsigned Length = Str.size();
651
652 // If there is a newline in this message somewhere, find that
653 // newline and split the message into the part before the newline
654 // (which will be word-wrapped) and the part from the newline one
655 // (which will be emitted unchanged).
656 for (unsigned I = 0; I != Length; ++I)
657 if (Str[I] == '\n') {
658 Length = I;
659 break;
660 }
661
662 // The string used to indent each line.
663 llvm::SmallString<16> IndentStr;
664 IndentStr.assign(Indentation, ' ');
665 bool Wrapped = false;
666 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
667 WordStart = WordEnd) {
668 // Find the beginning of the next word.
669 WordStart = skipWhitespace(WordStart, Str, Length);
670 if (WordStart == Length)
671 break;
672
673 // Find the end of this word.
674 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
675
676 // Does this word fit on the current line?
677 unsigned WordLength = WordEnd - WordStart;
678 if (Column + WordLength < Columns) {
679 // This word fits on the current line; print it there.
680 if (WordStart) {
681 OS << ' ';
682 Column += 1;
683 }
684 OS.write(&Str[WordStart], WordLength);
685 Column += WordLength;
686 continue;
687 }
688
689 // This word does not fit on the current line, so wrap to the next
690 // line.
691 OS << '\n';
692 OS.write(&IndentStr[0], Indentation);
693 OS.write(&Str[WordStart], WordLength);
694 Column = Indentation + WordLength;
695 Wrapped = true;
696 }
697
698 if (Length == Str.size())
699 return Wrapped; // We're done.
700
701 // There is a newline in the message, followed by something that
702 // will not be word-wrapped. Print that.
703 OS.write(&Str[Length], Str.size() - Length);
704 return true;
705}
706
707void TextDiagnosticPrinter::HandleDiagnostic(Diagnostic::Level Level,
708 const DiagnosticInfo &Info) {
709 // Keeps track of the the starting position of the location
710 // information (e.g., "foo.c:10:4:") that precedes the error
711 // message. We use this information to determine how long the
712 // file+line+column number prefix is.
713 uint64_t StartOfLocationInfo = OS.tell();
714
715 if (!Prefix.empty())
716 OS << Prefix << ": ";
717
718 // If the location is specified, print out a file/line/col and include trace
719 // if enabled.
720 if (Info.getLocation().isValid()) {
721 const SourceManager &SM = Info.getLocation().getManager();
722 PresumedLoc PLoc = SM.getPresumedLoc(Info.getLocation());
723 unsigned LineNo = PLoc.getLine();
724
725 // First, if this diagnostic is not in the main file, print out the
726 // "included from" lines.
727 if (LastWarningLoc != PLoc.getIncludeLoc()) {
728 LastWarningLoc = PLoc.getIncludeLoc();
729 PrintIncludeStack(LastWarningLoc, SM);
730 StartOfLocationInfo = OS.tell();
731 }
732
733 // Compute the column number.
734 if (DiagOpts->ShowLocation) {
735 if (DiagOpts->ShowColors)
736 OS.changeColor(savedColor, true);
737
738 // Emit a Visual Studio compatible line number syntax.
739 if (LangOpts && LangOpts->Microsoft) {
740 OS << PLoc.getFilename() << '(' << LineNo << ')';
741 OS << " : ";
742 } else {
743 OS << PLoc.getFilename() << ':' << LineNo << ':';
744 if (DiagOpts->ShowColumn)
745 if (unsigned ColNo = PLoc.getColumn())
746 OS << ColNo << ':';
747 }
748 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
749 FileID CaretFileID =
750 SM.getFileID(SM.getInstantiationLoc(Info.getLocation()));
751 bool PrintedRange = false;
752
753 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
754 // Ignore invalid ranges.
755 if (!Info.getRange(i).isValid()) continue;
756
757 SourceLocation B = Info.getRange(i).getBegin();
758 SourceLocation E = Info.getRange(i).getEnd();
759 B = SM.getInstantiationLoc(B);
760 E = SM.getInstantiationLoc(E);
761
762 // If the End location and the start location are the same and are a
763 // macro location, then the range was something that came from a macro
764 // expansion or _Pragma. If this is an object-like macro, the best we
765 // can do is to highlight the range. If this is a function-like
766 // macro, we'd also like to highlight the arguments.
767 if (B == E && Info.getRange(i).getEnd().isMacroID())
768 E = SM.getInstantiationRange(Info.getRange(i).getEnd()).second;
769
770 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
771 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
772
773 // If the start or end of the range is in another file, just discard
774 // it.
775 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
776 continue;
777
778 // Add in the length of the token, so that we cover multi-char tokens.
779 unsigned TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
780
781 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
782 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
783 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
784 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize) << '}';
785 PrintedRange = true;
786 }
787
788 if (PrintedRange)
789 OS << ':';
790 }
791 OS << ' ';
792 if (DiagOpts->ShowColors)
793 OS.resetColor();
794 }
795 }
796
797 if (DiagOpts->ShowColors) {
798 // Print diagnostic category in bold and color
799 switch (Level) {
800 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
801 case Diagnostic::Note: OS.changeColor(noteColor, true); break;
802 case Diagnostic::Warning: OS.changeColor(warningColor, true); break;
803 case Diagnostic::Error: OS.changeColor(errorColor, true); break;
804 case Diagnostic::Fatal: OS.changeColor(fatalColor, true); break;
805 }
806 }
807
808 switch (Level) {
809 case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
810 case Diagnostic::Note: OS << "note: "; break;
811 case Diagnostic::Warning: OS << "warning: "; break;
812 case Diagnostic::Error: OS << "error: "; break;
813 case Diagnostic::Fatal: OS << "fatal error: "; break;
814 }
815
816 if (DiagOpts->ShowColors)
817 OS.resetColor();
818
819 llvm::SmallString<100> OutStr;
820 Info.FormatDiagnostic(OutStr);
821
822 if (DiagOpts->ShowOptionNames) {
823 if (const char *Opt = Diagnostic::getWarningOptionForDiag(Info.getID())) {
824 OutStr += " [-W";
825 OutStr += Opt;
826 OutStr += ']';
827 } else {
828 // If the diagnostic is an extension diagnostic and not enabled by default
829 // then it must have been turned on with -pedantic.
830 bool EnabledByDefault;
831 if (Diagnostic::isBuiltinExtensionDiag(Info.getID(), EnabledByDefault) &&
832 !EnabledByDefault)
833 OutStr += " [-pedantic]";
834 }
835 }
836
837 if (DiagOpts->ShowColors) {
838 // Print warnings, errors and fatal errors in bold, no color
839 switch (Level) {
840 case Diagnostic::Warning: OS.changeColor(savedColor, true); break;
841 case Diagnostic::Error: OS.changeColor(savedColor, true); break;
842 case Diagnostic::Fatal: OS.changeColor(savedColor, true); break;
843 default: break; //don't bold notes
844 }
845 }
846
847 if (DiagOpts->MessageLength) {
848 // We will be word-wrapping the error message, so compute the
849 // column number where we currently are (after printing the
850 // location information).
851 unsigned Column = OS.tell() - StartOfLocationInfo;
852 PrintWordWrapped(OS, OutStr, DiagOpts->MessageLength, Column);
853 } else {
854 OS.write(OutStr.begin(), OutStr.size());
855 }
856 OS << '\n';
857 if (DiagOpts->ShowColors)
858 OS.resetColor();
859
860 // If caret diagnostics are enabled and we have location, we want to
861 // emit the caret. However, we only do this if the location moved
862 // from the last diagnostic, if the last diagnostic was a note that
863 // was part of a different warning or error diagnostic, or if the
864 // diagnostic has ranges. We don't want to emit the same caret
865 // multiple times if one loc has multiple diagnostics.
866 if (DiagOpts->ShowCarets && Info.getLocation().isValid() &&
867 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
868 (LastCaretDiagnosticWasNote && Level != Diagnostic::Note) ||
869 Info.getNumFixItHints())) {
870 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
871 LastLoc = Info.getLocation();
872 LastCaretDiagnosticWasNote = (Level == Diagnostic::Note);
873
874 // Get the ranges into a local array we can hack on.
875 SourceRange Ranges[20];
876 unsigned NumRanges = Info.getNumRanges();
877 assert(NumRanges < 20 && "Out of space");
878 for (unsigned i = 0; i != NumRanges; ++i)
879 Ranges[i] = Info.getRange(i);
880
881 unsigned NumHints = Info.getNumFixItHints();
882 for (unsigned idx = 0; idx < NumHints; ++idx) {
883 const FixItHint &Hint = Info.getFixItHint(idx);
884 if (Hint.RemoveRange.isValid()) {
885 assert(NumRanges < 20 && "Out of space");
886 Ranges[NumRanges++] = Hint.RemoveRange;
887 }
888 }
889
890 unsigned MacroInstSkipStart = 0, MacroInstSkipEnd = 0;
891 if (DiagOpts && DiagOpts->MacroBacktraceLimit && !LastLoc.isFileID()) {
892 // Compute the length of the macro-instantiation backtrace, so that we
893 // can establish which steps in the macro backtrace we'll skip.
894 SourceLocation Loc = LastLoc;
895 unsigned Depth = 0;
896 do {
897 ++Depth;
898 Loc = LastLoc.getManager().getImmediateInstantiationRange(Loc).first;
899 } while (!Loc.isFileID());
900
901 if (Depth > DiagOpts->MacroBacktraceLimit) {
902 MacroInstSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
903 DiagOpts->MacroBacktraceLimit % 2;
904 MacroInstSkipEnd = Depth - DiagOpts->MacroBacktraceLimit / 2;
905 }
906 }
907
908 EmitCaretDiagnostic(LastLoc, Ranges, NumRanges, LastLoc.getManager(),
909 Info.getFixItHints(),
910 Info.getNumFixItHints(),
911 DiagOpts->MessageLength,
912 0, MacroInstSkipStart, MacroInstSkipEnd);
913 }
914
915 OS.flush();
916}