blob: 259e05b47341dcf7cb70f79a96c2080a8414490f [file] [log] [blame]
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001//===--- TextDiagnostic.cpp - Text Diagnostic Pretty-Printing -------------===//
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#include "clang/Frontend/TextDiagnostic.h"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
13#include "clang/Frontend/DiagnosticOptions.h"
14#include "clang/Lex/Lexer.h"
15#include "llvm/Support/MemoryBuffer.h"
16#include "llvm/Support/raw_ostream.h"
17#include "llvm/Support/ErrorHandling.h"
18#include "llvm/ADT/SmallString.h"
19#include <algorithm>
20using namespace clang;
21
22static const enum raw_ostream::Colors noteColor =
23 raw_ostream::BLACK;
24static const enum raw_ostream::Colors fixitColor =
25 raw_ostream::GREEN;
26static const enum raw_ostream::Colors caretColor =
27 raw_ostream::GREEN;
28static const enum raw_ostream::Colors warningColor =
29 raw_ostream::MAGENTA;
30static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
31static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
32// Used for changing only the bold attribute.
33static const enum raw_ostream::Colors savedColor =
34 raw_ostream::SAVEDCOLOR;
35
36/// \brief Number of spaces to indent when word-wrapping.
37const unsigned WordWrapIndentation = 6;
38
39/// \brief When the source code line we want to print is too long for
40/// the terminal, select the "interesting" region.
Chandler Carruth7531f572011-10-15 23:54:09 +000041static void selectInterestingSourceRegion(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +000042 std::string &CaretLine,
43 std::string &FixItInsertionLine,
44 unsigned EndOfCaretToken,
45 unsigned Columns) {
46 unsigned MaxSize = std::max(SourceLine.size(),
47 std::max(CaretLine.size(),
48 FixItInsertionLine.size()));
49 if (MaxSize > SourceLine.size())
50 SourceLine.resize(MaxSize, ' ');
51 if (MaxSize > CaretLine.size())
52 CaretLine.resize(MaxSize, ' ');
53 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
54 FixItInsertionLine.resize(MaxSize, ' ');
55
56 // Find the slice that we need to display the full caret line
57 // correctly.
58 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
59 for (; CaretStart != CaretEnd; ++CaretStart)
60 if (!isspace(CaretLine[CaretStart]))
61 break;
62
63 for (; CaretEnd != CaretStart; --CaretEnd)
64 if (!isspace(CaretLine[CaretEnd - 1]))
65 break;
66
67 // Make sure we don't chop the string shorter than the caret token
68 // itself.
69 if (CaretEnd < EndOfCaretToken)
70 CaretEnd = EndOfCaretToken;
71
72 // If we have a fix-it line, make sure the slice includes all of the
73 // fix-it information.
74 if (!FixItInsertionLine.empty()) {
75 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
76 for (; FixItStart != FixItEnd; ++FixItStart)
77 if (!isspace(FixItInsertionLine[FixItStart]))
78 break;
79
80 for (; FixItEnd != FixItStart; --FixItEnd)
81 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
82 break;
83
84 if (FixItStart < CaretStart)
85 CaretStart = FixItStart;
86 if (FixItEnd > CaretEnd)
87 CaretEnd = FixItEnd;
88 }
89
90 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
91 // parts of the caret line. While this slice is smaller than the
92 // number of columns we have, try to grow the slice to encompass
93 // more context.
94
95 // If the end of the interesting region comes before we run out of
96 // space in the terminal, start at the beginning of the line.
97 if (Columns > 3 && CaretEnd < Columns - 3)
98 CaretStart = 0;
99
100 unsigned TargetColumns = Columns;
101 if (TargetColumns > 8)
102 TargetColumns -= 8; // Give us extra room for the ellipses.
103 unsigned SourceLength = SourceLine.size();
104 while ((CaretEnd - CaretStart) < TargetColumns) {
105 bool ExpandedRegion = false;
106 // Move the start of the interesting region left until we've
107 // pulled in something else interesting.
108 if (CaretStart == 1)
109 CaretStart = 0;
110 else if (CaretStart > 1) {
111 unsigned NewStart = CaretStart - 1;
112
113 // Skip over any whitespace we see here; we're looking for
114 // another bit of interesting text.
115 while (NewStart && isspace(SourceLine[NewStart]))
116 --NewStart;
117
118 // Skip over this bit of "interesting" text.
119 while (NewStart && !isspace(SourceLine[NewStart]))
120 --NewStart;
121
122 // Move up to the non-whitespace character we just saw.
123 if (NewStart)
124 ++NewStart;
125
126 // If we're still within our limit, update the starting
127 // position within the source/caret line.
128 if (CaretEnd - NewStart <= TargetColumns) {
129 CaretStart = NewStart;
130 ExpandedRegion = true;
131 }
132 }
133
134 // Move the end of the interesting region right until we've
135 // pulled in something else interesting.
136 if (CaretEnd != SourceLength) {
137 assert(CaretEnd < SourceLength && "Unexpected caret position!");
138 unsigned NewEnd = CaretEnd;
139
140 // Skip over any whitespace we see here; we're looking for
141 // another bit of interesting text.
142 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
143 ++NewEnd;
144
145 // Skip over this bit of "interesting" text.
146 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
147 ++NewEnd;
148
149 if (NewEnd - CaretStart <= TargetColumns) {
150 CaretEnd = NewEnd;
151 ExpandedRegion = true;
152 }
153 }
154
155 if (!ExpandedRegion)
156 break;
157 }
158
159 // [CaretStart, CaretEnd) is the slice we want. Update the various
160 // output lines to show only this slice, with two-space padding
161 // before the lines so that it looks nicer.
162 if (CaretEnd < SourceLine.size())
163 SourceLine.replace(CaretEnd, std::string::npos, "...");
164 if (CaretEnd < CaretLine.size())
165 CaretLine.erase(CaretEnd, std::string::npos);
166 if (FixItInsertionLine.size() > CaretEnd)
167 FixItInsertionLine.erase(CaretEnd, std::string::npos);
168
169 if (CaretStart > 2) {
170 SourceLine.replace(0, CaretStart, " ...");
171 CaretLine.replace(0, CaretStart, " ");
172 if (FixItInsertionLine.size() >= CaretStart)
173 FixItInsertionLine.replace(0, CaretStart, " ");
174 }
175}
176
177/// Look through spelling locations for a macro argument expansion, and
178/// if found skip to it so that we can trace the argument rather than the macros
179/// in which that argument is used. If no macro argument expansion is found,
180/// don't skip anything and return the starting location.
181static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
182 SourceLocation StartLoc) {
183 for (SourceLocation L = StartLoc; L.isMacroID();
184 L = SM.getImmediateSpellingLoc(L)) {
185 if (SM.isMacroArgExpansion(L))
186 return L;
187 }
188
189 // Otherwise just return initial location, there's nothing to skip.
190 return StartLoc;
191}
192
193/// Gets the location of the immediate macro caller, one level up the stack
194/// toward the initial macro typed into the source.
195static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
196 SourceLocation Loc) {
197 if (!Loc.isMacroID()) return Loc;
198
199 // When we have the location of (part of) an expanded parameter, its spelling
200 // location points to the argument as typed into the macro call, and
201 // therefore is used to locate the macro caller.
202 if (SM.isMacroArgExpansion(Loc))
203 return SM.getImmediateSpellingLoc(Loc);
204
205 // Otherwise, the caller of the macro is located where this macro is
206 // expanded (while the spelling is part of the macro definition).
207 return SM.getImmediateExpansionRange(Loc).first;
208}
209
210/// Gets the location of the immediate macro callee, one level down the stack
211/// toward the leaf macro.
212static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
213 SourceLocation Loc) {
214 if (!Loc.isMacroID()) return Loc;
215
216 // When we have the location of (part of) an expanded parameter, its
217 // expansion location points to the unexpanded paramater reference within
218 // the macro definition (or callee).
219 if (SM.isMacroArgExpansion(Loc))
220 return SM.getImmediateExpansionRange(Loc).first;
221
222 // Otherwise, the callee of the macro is located where this location was
223 // spelled inside the macro definition.
224 return SM.getImmediateSpellingLoc(Loc);
225}
226
227/// Get the presumed location of a diagnostic message. This computes the
228/// presumed location for the top of any macro backtrace when present.
229static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
230 SourceLocation Loc) {
Chandler Carruth7531f572011-10-15 23:54:09 +0000231 // This is a condensed form of the algorithm used by emitCaretDiagnostic to
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000232 // walk to the top of the macro call stack.
233 while (Loc.isMacroID()) {
234 Loc = skipToMacroArgExpansion(SM, Loc);
235 Loc = getImmediateMacroCallerLoc(SM, Loc);
236 }
237
238 return SM.getPresumedLoc(Loc);
239}
240
241/// \brief Skip over whitespace in the string, starting at the given
242/// index.
243///
244/// \returns The index of the first non-whitespace character that is
245/// greater than or equal to Idx or, if no such character exists,
246/// returns the end of the string.
247static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
248 while (Idx < Length && isspace(Str[Idx]))
249 ++Idx;
250 return Idx;
251}
252
253/// \brief If the given character is the start of some kind of
254/// balanced punctuation (e.g., quotes or parentheses), return the
255/// character that will terminate the punctuation.
256///
257/// \returns The ending punctuation character, if any, or the NULL
258/// character if the input character does not start any punctuation.
259static inline char findMatchingPunctuation(char c) {
260 switch (c) {
261 case '\'': return '\'';
262 case '`': return '\'';
263 case '"': return '"';
264 case '(': return ')';
265 case '[': return ']';
266 case '{': return '}';
267 default: break;
268 }
269
270 return 0;
271}
272
273/// \brief Find the end of the word starting at the given offset
274/// within a string.
275///
276/// \returns the index pointing one character past the end of the
277/// word.
278static unsigned findEndOfWord(unsigned Start, StringRef Str,
279 unsigned Length, unsigned Column,
280 unsigned Columns) {
281 assert(Start < Str.size() && "Invalid start position!");
282 unsigned End = Start + 1;
283
284 // If we are already at the end of the string, take that as the word.
285 if (End == Str.size())
286 return End;
287
288 // Determine if the start of the string is actually opening
289 // punctuation, e.g., a quote or parentheses.
290 char EndPunct = findMatchingPunctuation(Str[Start]);
291 if (!EndPunct) {
292 // This is a normal word. Just find the first space character.
293 while (End < Length && !isspace(Str[End]))
294 ++End;
295 return End;
296 }
297
298 // We have the start of a balanced punctuation sequence (quotes,
299 // parentheses, etc.). Determine the full sequence is.
300 llvm::SmallString<16> PunctuationEndStack;
301 PunctuationEndStack.push_back(EndPunct);
302 while (End < Length && !PunctuationEndStack.empty()) {
303 if (Str[End] == PunctuationEndStack.back())
304 PunctuationEndStack.pop_back();
305 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
306 PunctuationEndStack.push_back(SubEndPunct);
307
308 ++End;
309 }
310
311 // Find the first space character after the punctuation ended.
312 while (End < Length && !isspace(Str[End]))
313 ++End;
314
315 unsigned PunctWordLength = End - Start;
316 if (// If the word fits on this line
317 Column + PunctWordLength <= Columns ||
318 // ... or the word is "short enough" to take up the next line
319 // without too much ugly white space
320 PunctWordLength < Columns/3)
321 return End; // Take the whole thing as a single "word".
322
323 // The whole quoted/parenthesized string is too long to print as a
324 // single "word". Instead, find the "word" that starts just after
325 // the punctuation and use that end-point instead. This will recurse
326 // until it finds something small enough to consider a word.
327 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
328}
329
330/// \brief Print the given string to a stream, word-wrapping it to
331/// some number of columns in the process.
332///
333/// \param OS the stream to which the word-wrapping string will be
334/// emitted.
335/// \param Str the string to word-wrap and output.
336/// \param Columns the number of columns to word-wrap to.
337/// \param Column the column number at which the first character of \p
338/// Str will be printed. This will be non-zero when part of the first
339/// line has already been printed.
340/// \param Indentation the number of spaces to indent any lines beyond
341/// the first line.
342/// \returns true if word-wrapping was required, or false if the
343/// string fit on the first line.
344static bool printWordWrapped(raw_ostream &OS, StringRef Str,
345 unsigned Columns,
346 unsigned Column = 0,
347 unsigned Indentation = WordWrapIndentation) {
348 const unsigned Length = std::min(Str.find('\n'), Str.size());
349
350 // The string used to indent each line.
351 llvm::SmallString<16> IndentStr;
352 IndentStr.assign(Indentation, ' ');
353 bool Wrapped = false;
354 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
355 WordStart = WordEnd) {
356 // Find the beginning of the next word.
357 WordStart = skipWhitespace(WordStart, Str, Length);
358 if (WordStart == Length)
359 break;
360
361 // Find the end of this word.
362 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
363
364 // Does this word fit on the current line?
365 unsigned WordLength = WordEnd - WordStart;
366 if (Column + WordLength < Columns) {
367 // This word fits on the current line; print it there.
368 if (WordStart) {
369 OS << ' ';
370 Column += 1;
371 }
372 OS << Str.substr(WordStart, WordLength);
373 Column += WordLength;
374 continue;
375 }
376
377 // This word does not fit on the current line, so wrap to the next
378 // line.
379 OS << '\n';
380 OS.write(&IndentStr[0], Indentation);
381 OS << Str.substr(WordStart, WordLength);
382 Column = Indentation + WordLength;
383 Wrapped = true;
384 }
385
386 // Append any remaning text from the message with its existing formatting.
387 OS << Str.substr(Length);
388
389 return Wrapped;
390}
391
392TextDiagnostic::TextDiagnostic(raw_ostream &OS,
393 const SourceManager &SM,
394 const LangOptions &LangOpts,
Chandler Carruth21a869a2011-10-16 02:57:39 +0000395 const DiagnosticOptions &DiagOpts)
396 : OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {
397}
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000398
Chandler Carruth7531f572011-10-15 23:54:09 +0000399void TextDiagnostic::emitDiagnostic(SourceLocation Loc,
400 DiagnosticsEngine::Level Level,
401 StringRef Message,
402 ArrayRef<CharSourceRange> Ranges,
403 ArrayRef<FixItHint> FixItHints,
404 bool LastCaretDiagnosticWasNote) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000405 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
406
407 // First, if this diagnostic is not in the main file, print out the
408 // "included from" lines.
409 emitIncludeStack(PLoc.getIncludeLoc(), Level);
410
411 uint64_t StartOfLocationInfo = OS.tell();
412
413 // Next emit the location of this particular diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000414 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000415
416 if (DiagOpts.ShowColors)
417 OS.resetColor();
418
419 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
420 printDiagnosticMessage(OS, Level, Message,
421 OS.tell() - StartOfLocationInfo,
422 DiagOpts.MessageLength, DiagOpts.ShowColors);
423
424 // If caret diagnostics are enabled and we have location, we want to
425 // emit the caret. However, we only do this if the location moved
426 // from the last diagnostic, if the last diagnostic was a note that
427 // was part of a different warning or error diagnostic, or if the
428 // diagnostic has ranges. We don't want to emit the same caret
429 // multiple times if one loc has multiple diagnostics.
430 if (DiagOpts.ShowCarets &&
431 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
432 (LastLevel == DiagnosticsEngine::Note && Level != LastLevel))) {
433 // Get the ranges into a local array we can hack on.
434 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
435 Ranges.end());
436
437 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
438 E = FixItHints.end();
439 I != E; ++I)
440 if (I->RemoveRange.isValid())
441 MutableRanges.push_back(I->RemoveRange);
442
443 unsigned MacroDepth = 0;
Chandler Carruth7531f572011-10-15 23:54:09 +0000444 emitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000445 }
446
447 LastLoc = Loc;
448 LastLevel = Level;
449}
450
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000451/*static*/ void
452TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
453 DiagnosticsEngine::Level Level,
454 bool ShowColors) {
455 if (ShowColors) {
456 // Print diagnostic category in bold and color
457 switch (Level) {
458 case DiagnosticsEngine::Ignored:
459 llvm_unreachable("Invalid diagnostic type");
460 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
461 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
462 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
463 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
464 }
465 }
466
467 switch (Level) {
468 case DiagnosticsEngine::Ignored:
469 llvm_unreachable("Invalid diagnostic type");
470 case DiagnosticsEngine::Note: OS << "note: "; break;
471 case DiagnosticsEngine::Warning: OS << "warning: "; break;
472 case DiagnosticsEngine::Error: OS << "error: "; break;
473 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
474 }
475
476 if (ShowColors)
477 OS.resetColor();
478}
479
480/*static*/ void
481TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
482 DiagnosticsEngine::Level Level,
483 StringRef Message,
484 unsigned CurrentColumn, unsigned Columns,
485 bool ShowColors) {
486 if (ShowColors) {
487 // Print warnings, errors and fatal errors in bold, no color
488 switch (Level) {
489 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
490 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
491 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
492 default: break; //don't bold notes
493 }
494 }
495
496 if (Columns)
497 printWordWrapped(OS, Message, Columns, CurrentColumn);
498 else
499 OS << Message;
500
501 if (ShowColors)
502 OS.resetColor();
503 OS << '\n';
504}
505
506/// \brief Prints an include stack when appropriate for a particular
507/// diagnostic level and location.
508///
509/// This routine handles all the logic of suppressing particular include
510/// stacks (such as those for notes) and duplicate include stacks when
511/// repeated warnings occur within the same file. It also handles the logic
512/// of customizing the formatting and display of the include stack.
513///
514/// \param Level The diagnostic level of the message this stack pertains to.
515/// \param Loc The include location of the current file (not the diagnostic
516/// location).
517void TextDiagnostic::emitIncludeStack(SourceLocation Loc,
518 DiagnosticsEngine::Level Level) {
519 // Skip redundant include stacks altogether.
520 if (LastIncludeLoc == Loc)
521 return;
522 LastIncludeLoc = Loc;
523
524 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
525 return;
526
527 emitIncludeStackRecursively(Loc);
528}
529
530/// \brief Helper to recursivly walk up the include stack and print each layer
531/// on the way back down.
532void TextDiagnostic::emitIncludeStackRecursively(SourceLocation Loc) {
533 if (Loc.isInvalid())
534 return;
535
536 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
537 if (PLoc.isInvalid())
538 return;
539
540 // Emit the other include frames first.
541 emitIncludeStackRecursively(PLoc.getIncludeLoc());
542
543 if (DiagOpts.ShowLocation)
544 OS << "In file included from " << PLoc.getFilename()
545 << ':' << PLoc.getLine() << ":\n";
546 else
547 OS << "In included file:\n";
548}
549
550/// \brief Print out the file/line/column information and include trace.
551///
552/// This method handlen the emission of the diagnostic location information.
553/// This includes extracting as much location information as is present for
554/// the diagnostic and printing it, as well as any include stack or source
555/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000556void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000557 DiagnosticsEngine::Level Level,
558 ArrayRef<CharSourceRange> Ranges) {
559 if (PLoc.isInvalid()) {
560 // At least print the file name if available:
561 FileID FID = SM.getFileID(Loc);
562 if (!FID.isInvalid()) {
563 const FileEntry* FE = SM.getFileEntryForID(FID);
564 if (FE && FE->getName()) {
565 OS << FE->getName();
566 if (FE->getDevice() == 0 && FE->getInode() == 0
567 && FE->getFileMode() == 0) {
568 // in PCH is a guess, but a good one:
569 OS << " (in PCH)";
570 }
571 OS << ": ";
572 }
573 }
574 return;
575 }
576 unsigned LineNo = PLoc.getLine();
577
578 if (!DiagOpts.ShowLocation)
579 return;
580
581 if (DiagOpts.ShowColors)
582 OS.changeColor(savedColor, true);
583
584 OS << PLoc.getFilename();
585 switch (DiagOpts.Format) {
586 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
587 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
588 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
589 }
590
591 if (DiagOpts.ShowColumn)
592 // Compute the column number.
593 if (unsigned ColNo = PLoc.getColumn()) {
594 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
595 OS << ',';
596 ColNo--;
597 } else
598 OS << ':';
599 OS << ColNo;
600 }
601 switch (DiagOpts.Format) {
602 case DiagnosticOptions::Clang:
603 case DiagnosticOptions::Vi: OS << ':'; break;
604 case DiagnosticOptions::Msvc: OS << ") : "; break;
605 }
606
607 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
608 FileID CaretFileID =
609 SM.getFileID(SM.getExpansionLoc(Loc));
610 bool PrintedRange = false;
611
612 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
613 RE = Ranges.end();
614 RI != RE; ++RI) {
615 // Ignore invalid ranges.
616 if (!RI->isValid()) continue;
617
618 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
619 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
620
621 // If the End location and the start location are the same and are a
622 // macro location, then the range was something that came from a
623 // macro expansion or _Pragma. If this is an object-like macro, the
624 // best we can do is to highlight the range. If this is a
625 // function-like macro, we'd also like to highlight the arguments.
626 if (B == E && RI->getEnd().isMacroID())
627 E = SM.getExpansionRange(RI->getEnd()).second;
628
629 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
630 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
631
632 // If the start or end of the range is in another file, just discard
633 // it.
634 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
635 continue;
636
637 // Add in the length of the token, so that we cover multi-char
638 // tokens.
639 unsigned TokSize = 0;
640 if (RI->isTokenRange())
641 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
642
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 << '}';
648 PrintedRange = true;
649 }
650
651 if (PrintedRange)
652 OS << ':';
653 }
654 OS << ' ';
655}
656
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000657/// \brief Emit the caret and underlining text.
658///
659/// Walks up the macro expansion stack printing the code snippet, caret,
660/// underlines and FixItHint display as appropriate at each level. Walk is
661/// accomplished by calling itself recursively.
662///
663/// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
664/// caret diagnostics.
665/// FIXME: Break up massive function into logical units.
666///
667/// \param Loc The location for this caret.
668/// \param Ranges The underlined ranges for this code snippet.
669/// \param Hints The FixIt hints active for this diagnostic.
670/// \param MacroSkipEnd The depth to stop skipping macro expansions.
671/// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth7531f572011-10-15 23:54:09 +0000672void TextDiagnostic::emitCaret(SourceLocation Loc,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000673 SmallVectorImpl<CharSourceRange>& Ranges,
674 ArrayRef<FixItHint> Hints,
675 unsigned &MacroDepth,
676 unsigned OnMacroInst) {
677 assert(!Loc.isInvalid() && "must have a valid source location here");
678
679 // If this is a file source location, directly emit the source snippet and
680 // caret line. Also record the macro depth reached.
681 if (Loc.isFileID()) {
682 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
683 MacroDepth = OnMacroInst;
Chandler Carruth7531f572011-10-15 23:54:09 +0000684 emitSnippetAndCaret(Loc, Ranges, Hints);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000685 return;
686 }
687 // Otherwise recurse through each macro expansion layer.
688
689 // When processing macros, skip over the expansions leading up to
690 // a macro argument, and trace the argument's expansion stack instead.
691 Loc = skipToMacroArgExpansion(SM, Loc);
692
693 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
694
695 // FIXME: Map ranges?
Chandler Carruth7531f572011-10-15 23:54:09 +0000696 emitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000697
698 // Map the location.
699 Loc = getImmediateMacroCalleeLoc(SM, Loc);
700
701 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
702 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
703 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
704 DiagOpts.MacroBacktraceLimit % 2;
705 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
706 }
707
708 // Whether to suppress printing this macro expansion.
709 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
710 OnMacroInst < MacroSkipEnd);
711
712 // Map the ranges.
713 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
714 E = Ranges.end();
715 I != E; ++I) {
716 SourceLocation Start = I->getBegin(), End = I->getEnd();
717 if (Start.isMacroID())
718 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
719 if (End.isMacroID())
720 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
721 }
722
723 if (!Suppressed) {
724 // Don't print recursive expansion notes from an expansion note.
725 Loc = SM.getSpellingLoc(Loc);
726
727 // Get the pretty name, according to #line directives etc.
728 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
729 if (PLoc.isInvalid())
730 return;
731
732 // If this diagnostic is not in the main file, print out the
733 // "included from" lines.
734 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
735
736 if (DiagOpts.ShowLocation) {
737 // Emit the file/line/column that this expansion came from.
738 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
739 if (DiagOpts.ShowColumn)
740 OS << PLoc.getColumn() << ':';
741 OS << ' ';
742 }
743 OS << "note: expanded from:\n";
744
Chandler Carruth7531f572011-10-15 23:54:09 +0000745 emitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000746 return;
747 }
748
749 if (OnMacroInst == MacroSkipStart) {
750 // Tell the user that we've skipped contexts.
751 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
752 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
753 "all)\n";
754 }
755}
756
757/// \brief Emit a code snippet and caret line.
758///
759/// This routine emits a single line's code snippet and caret line..
760///
761/// \param Loc The location for the caret.
762/// \param Ranges The underlined ranges for this code snippet.
763/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000764void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000765 SourceLocation Loc,
766 SmallVectorImpl<CharSourceRange>& Ranges,
767 ArrayRef<FixItHint> Hints) {
768 assert(!Loc.isInvalid() && "must have a valid source location here");
769 assert(Loc.isFileID() && "must have a file location here");
770
771 // Decompose the location into a FID/Offset pair.
772 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
773 FileID FID = LocInfo.first;
774 unsigned FileOffset = LocInfo.second;
775
776 // Get information about the buffer it points into.
777 bool Invalid = false;
778 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
779 if (Invalid)
780 return;
781
782 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
783 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
784 unsigned CaretEndColNo
785 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
786
787 // Rewind from the current position to the start of the line.
788 const char *TokPtr = BufStart+FileOffset;
789 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
790
791
792 // Compute the line end. Scan forward from the error position to the end of
793 // the line.
794 const char *LineEnd = TokPtr;
795 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
796 ++LineEnd;
797
798 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
799 // the source line length as currently being computed. See
800 // test/Misc/message-length.c.
801 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
802
803 // Copy the line of code into an std::string for ease of manipulation.
804 std::string SourceLine(LineStart, LineEnd);
805
806 // Create a line for the caret that is filled with spaces that is the same
807 // length as the line of source code.
808 std::string CaretLine(LineEnd-LineStart, ' ');
809
810 // Highlight all of the characters covered by Ranges with ~ characters.
811 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
812 E = Ranges.end();
813 I != E; ++I)
Chandler Carruth7531f572011-10-15 23:54:09 +0000814 highlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000815
816 // Next, insert the caret itself.
817 if (ColNo-1 < CaretLine.size())
818 CaretLine[ColNo-1] = '^';
819 else
820 CaretLine.push_back('^');
821
Chandler Carruth7531f572011-10-15 23:54:09 +0000822 expandTabs(SourceLine, CaretLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000823
824 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
825 // to produce easily machine parsable output. Add a space before the
826 // source line and the caret to make it trivial to tell the main diagnostic
827 // line from what the user is intended to see.
828 if (DiagOpts.ShowSourceRanges) {
829 SourceLine = ' ' + SourceLine;
830 CaretLine = ' ' + CaretLine;
831 }
832
Chandler Carruth7531f572011-10-15 23:54:09 +0000833 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000834 LineStart, LineEnd,
835 Hints);
836
837 // If the source line is too long for our terminal, select only the
838 // "interesting" source region within that line.
839 unsigned Columns = DiagOpts.MessageLength;
840 if (Columns && SourceLine.size() > Columns)
Chandler Carruth7531f572011-10-15 23:54:09 +0000841 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000842 CaretEndColNo, Columns);
843
844 // Finally, remove any blank spaces from the end of CaretLine.
845 while (CaretLine[CaretLine.size()-1] == ' ')
846 CaretLine.erase(CaretLine.end()-1);
847
848 // Emit what we have computed.
849 OS << SourceLine << '\n';
850
851 if (DiagOpts.ShowColors)
852 OS.changeColor(caretColor, true);
853 OS << CaretLine << '\n';
854 if (DiagOpts.ShowColors)
855 OS.resetColor();
856
857 if (!FixItInsertionLine.empty()) {
858 if (DiagOpts.ShowColors)
859 // Print fixit line in color
860 OS.changeColor(fixitColor, false);
861 if (DiagOpts.ShowSourceRanges)
862 OS << ' ';
863 OS << FixItInsertionLine << '\n';
864 if (DiagOpts.ShowColors)
865 OS.resetColor();
866 }
867
868 // Print out any parseable fixit information requested by the options.
Chandler Carruth7531f572011-10-15 23:54:09 +0000869 emitParseableFixits(Hints);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000870}
871
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000872/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +0000873void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000874 unsigned LineNo, FileID FID,
875 const std::string &SourceLine,
876 std::string &CaretLine) {
877 assert(CaretLine.size() == SourceLine.size() &&
878 "Expect a correspondence between source and caret line!");
879 if (!R.isValid()) return;
880
881 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
882 SourceLocation End = SM.getExpansionLoc(R.getEnd());
883
884 // If the End location and the start location are the same and are a macro
885 // location, then the range was something that came from a macro expansion
886 // or _Pragma. If this is an object-like macro, the best we can do is to
887 // highlight the range. If this is a function-like macro, we'd also like to
888 // highlight the arguments.
889 if (Begin == End && R.getEnd().isMacroID())
890 End = SM.getExpansionRange(R.getEnd()).second;
891
892 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
893 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
894 return; // No intersection.
895
896 unsigned EndLineNo = SM.getExpansionLineNumber(End);
897 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
898 return; // No intersection.
899
900 // Compute the column number of the start.
901 unsigned StartColNo = 0;
902 if (StartLineNo == LineNo) {
903 StartColNo = SM.getExpansionColumnNumber(Begin);
904 if (StartColNo) --StartColNo; // Zero base the col #.
905 }
906
907 // Compute the column number of the end.
908 unsigned EndColNo = CaretLine.size();
909 if (EndLineNo == LineNo) {
910 EndColNo = SM.getExpansionColumnNumber(End);
911 if (EndColNo) {
912 --EndColNo; // Zero base the col #.
913
914 // Add in the length of the token, so that we cover multi-char tokens if
915 // this is a token range.
916 if (R.isTokenRange())
917 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
918 } else {
919 EndColNo = CaretLine.size();
920 }
921 }
922
923 assert(StartColNo <= EndColNo && "Invalid range!");
924
925 // Check that a token range does not highlight only whitespace.
926 if (R.isTokenRange()) {
927 // Pick the first non-whitespace column.
928 while (StartColNo < SourceLine.size() &&
929 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
930 ++StartColNo;
931
932 // Pick the last non-whitespace column.
933 if (EndColNo > SourceLine.size())
934 EndColNo = SourceLine.size();
935 while (EndColNo-1 &&
936 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
937 --EndColNo;
938
939 // If the start/end passed each other, then we are trying to highlight a
940 // range that just exists in whitespace, which must be some sort of other
941 // bug.
942 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
943 }
944
945 // Fill the range with ~'s.
946 for (unsigned i = StartColNo; i < EndColNo; ++i)
947 CaretLine[i] = '~';
948}
949
Chandler Carruth7531f572011-10-15 23:54:09 +0000950std::string TextDiagnostic::buildFixItInsertionLine(unsigned LineNo,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000951 const char *LineStart,
952 const char *LineEnd,
953 ArrayRef<FixItHint> Hints) {
954 std::string FixItInsertionLine;
955 if (Hints.empty() || !DiagOpts.ShowFixits)
956 return FixItInsertionLine;
957
958 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
959 I != E; ++I) {
960 if (!I->CodeToInsert.empty()) {
961 // We have an insertion hint. Determine whether the inserted
962 // code is on the same line as the caret.
963 std::pair<FileID, unsigned> HintLocInfo
964 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
965 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
966 // Insert the new code into the line just below the code
967 // that the user wrote.
968 unsigned HintColNo
969 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
970 unsigned LastColumnModified
971 = HintColNo - 1 + I->CodeToInsert.size();
972 if (LastColumnModified > FixItInsertionLine.size())
973 FixItInsertionLine.resize(LastColumnModified, ' ');
974 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
975 FixItInsertionLine.begin() + HintColNo - 1);
976 } else {
977 FixItInsertionLine.clear();
978 break;
979 }
980 }
981 }
982
983 if (FixItInsertionLine.empty())
984 return FixItInsertionLine;
985
986 // Now that we have the entire fixit line, expand the tabs in it.
987 // Since we don't want to insert spaces in the middle of a word,
988 // find each word and the column it should line up with and insert
989 // spaces until they match.
990 unsigned FixItPos = 0;
991 unsigned LinePos = 0;
992 unsigned TabExpandedCol = 0;
993 unsigned LineLength = LineEnd - LineStart;
994
995 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
996 // Find the next word in the FixIt line.
997 while (FixItPos < FixItInsertionLine.size() &&
998 FixItInsertionLine[FixItPos] == ' ')
999 ++FixItPos;
1000 unsigned CharDistance = FixItPos - TabExpandedCol;
1001
1002 // Walk forward in the source line, keeping track of
1003 // the tab-expanded column.
1004 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1005 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1006 ++TabExpandedCol;
1007 else
1008 TabExpandedCol =
1009 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1010
1011 // Adjust the fixit line to match this column.
1012 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1013 FixItPos = TabExpandedCol;
1014
1015 // Walk to the end of the word.
1016 while (FixItPos < FixItInsertionLine.size() &&
1017 FixItInsertionLine[FixItPos] != ' ')
1018 ++FixItPos;
1019 }
1020
1021 return FixItInsertionLine;
1022}
1023
Chandler Carruth7531f572011-10-15 23:54:09 +00001024void TextDiagnostic::expandTabs(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001025 std::string &CaretLine) {
1026 // Scan the source line, looking for tabs. If we find any, manually expand
1027 // them to spaces and update the CaretLine to match.
1028 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1029 if (SourceLine[i] != '\t') continue;
1030
1031 // Replace this tab with at least one space.
1032 SourceLine[i] = ' ';
1033
1034 // Compute the number of spaces we need to insert.
1035 unsigned TabStop = DiagOpts.TabStop;
1036 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1037 "Invalid -ftabstop value");
1038 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1039 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1040
1041 // Insert spaces into the SourceLine.
1042 SourceLine.insert(i+1, NumSpaces, ' ');
1043
1044 // Insert spaces or ~'s into CaretLine.
1045 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1046 }
1047}
1048
Chandler Carruth7531f572011-10-15 23:54:09 +00001049void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001050 if (!DiagOpts.ShowParseableFixits)
1051 return;
1052
1053 // We follow FixItRewriter's example in not (yet) handling
1054 // fix-its in macros.
1055 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1056 I != E; ++I) {
1057 if (I->RemoveRange.isInvalid() ||
1058 I->RemoveRange.getBegin().isMacroID() ||
1059 I->RemoveRange.getEnd().isMacroID())
1060 return;
1061 }
1062
1063 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1064 I != E; ++I) {
1065 SourceLocation BLoc = I->RemoveRange.getBegin();
1066 SourceLocation ELoc = I->RemoveRange.getEnd();
1067
1068 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1069 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1070
1071 // Adjust for token ranges.
1072 if (I->RemoveRange.isTokenRange())
1073 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1074
1075 // We specifically do not do word-wrapping or tab-expansion here,
1076 // because this is supposed to be easy to parse.
1077 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1078 if (PLoc.isInvalid())
1079 break;
1080
1081 OS << "fix-it:\"";
1082 OS.write_escaped(PLoc.getFilename());
1083 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1084 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1085 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1086 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1087 << "}:\"";
1088 OS.write_escaped(I->CodeToInsert);
1089 OS << "\"\n";
1090 }
1091}
1092