blob: 9bae0dff938a5ea073967562ff4e85bc10bce0be [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,
Chandler Carruth2ed34952011-10-16 06:24:58 +0000403 ArrayRef<FixItHint> FixItHints) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000404 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
405
406 // First, if this diagnostic is not in the main file, print out the
407 // "included from" lines.
408 emitIncludeStack(PLoc.getIncludeLoc(), Level);
409
410 uint64_t StartOfLocationInfo = OS.tell();
411
412 // Next emit the location of this particular diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000413 emitDiagnosticLoc(Loc, PLoc, Level, Ranges);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000414
415 if (DiagOpts.ShowColors)
416 OS.resetColor();
417
418 printDiagnosticLevel(OS, Level, DiagOpts.ShowColors);
419 printDiagnosticMessage(OS, Level, Message,
420 OS.tell() - StartOfLocationInfo,
421 DiagOpts.MessageLength, DiagOpts.ShowColors);
422
423 // If caret diagnostics are enabled and we have location, we want to
424 // emit the caret. However, we only do this if the location moved
425 // from the last diagnostic, if the last diagnostic was a note that
426 // was part of a different warning or error diagnostic, or if the
427 // diagnostic has ranges. We don't want to emit the same caret
428 // multiple times if one loc has multiple diagnostics.
429 if (DiagOpts.ShowCarets &&
430 (Loc != LastLoc || !Ranges.empty() || !FixItHints.empty() ||
431 (LastLevel == DiagnosticsEngine::Note && Level != LastLevel))) {
432 // Get the ranges into a local array we can hack on.
433 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
434 Ranges.end());
435
436 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
437 E = FixItHints.end();
438 I != E; ++I)
439 if (I->RemoveRange.isValid())
440 MutableRanges.push_back(I->RemoveRange);
441
442 unsigned MacroDepth = 0;
Chandler Carruth7531f572011-10-15 23:54:09 +0000443 emitCaret(Loc, MutableRanges, FixItHints, MacroDepth);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000444 }
445
446 LastLoc = Loc;
447 LastLevel = Level;
448}
449
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000450/*static*/ void
451TextDiagnostic::printDiagnosticLevel(raw_ostream &OS,
452 DiagnosticsEngine::Level Level,
453 bool ShowColors) {
454 if (ShowColors) {
455 // Print diagnostic category in bold and color
456 switch (Level) {
457 case DiagnosticsEngine::Ignored:
458 llvm_unreachable("Invalid diagnostic type");
459 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
460 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
461 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
462 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
463 }
464 }
465
466 switch (Level) {
467 case DiagnosticsEngine::Ignored:
468 llvm_unreachable("Invalid diagnostic type");
469 case DiagnosticsEngine::Note: OS << "note: "; break;
470 case DiagnosticsEngine::Warning: OS << "warning: "; break;
471 case DiagnosticsEngine::Error: OS << "error: "; break;
472 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
473 }
474
475 if (ShowColors)
476 OS.resetColor();
477}
478
479/*static*/ void
480TextDiagnostic::printDiagnosticMessage(raw_ostream &OS,
481 DiagnosticsEngine::Level Level,
482 StringRef Message,
483 unsigned CurrentColumn, unsigned Columns,
484 bool ShowColors) {
485 if (ShowColors) {
486 // Print warnings, errors and fatal errors in bold, no color
487 switch (Level) {
488 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
489 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
490 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
491 default: break; //don't bold notes
492 }
493 }
494
495 if (Columns)
496 printWordWrapped(OS, Message, Columns, CurrentColumn);
497 else
498 OS << Message;
499
500 if (ShowColors)
501 OS.resetColor();
502 OS << '\n';
503}
504
505/// \brief Prints an include stack when appropriate for a particular
506/// diagnostic level and location.
507///
508/// This routine handles all the logic of suppressing particular include
509/// stacks (such as those for notes) and duplicate include stacks when
510/// repeated warnings occur within the same file. It also handles the logic
511/// of customizing the formatting and display of the include stack.
512///
513/// \param Level The diagnostic level of the message this stack pertains to.
514/// \param Loc The include location of the current file (not the diagnostic
515/// location).
516void TextDiagnostic::emitIncludeStack(SourceLocation Loc,
517 DiagnosticsEngine::Level Level) {
518 // Skip redundant include stacks altogether.
519 if (LastIncludeLoc == Loc)
520 return;
521 LastIncludeLoc = Loc;
522
523 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
524 return;
525
526 emitIncludeStackRecursively(Loc);
527}
528
529/// \brief Helper to recursivly walk up the include stack and print each layer
530/// on the way back down.
531void TextDiagnostic::emitIncludeStackRecursively(SourceLocation Loc) {
532 if (Loc.isInvalid())
533 return;
534
535 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
536 if (PLoc.isInvalid())
537 return;
538
539 // Emit the other include frames first.
540 emitIncludeStackRecursively(PLoc.getIncludeLoc());
541
542 if (DiagOpts.ShowLocation)
543 OS << "In file included from " << PLoc.getFilename()
544 << ':' << PLoc.getLine() << ":\n";
545 else
546 OS << "In included file:\n";
547}
548
549/// \brief Print out the file/line/column information and include trace.
550///
551/// This method handlen the emission of the diagnostic location information.
552/// This includes extracting as much location information as is present for
553/// the diagnostic and printing it, as well as any include stack or source
554/// ranges necessary.
Chandler Carruth7531f572011-10-15 23:54:09 +0000555void TextDiagnostic::emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
Chandler Carruth6ddd8872011-10-15 23:48:02 +0000556 DiagnosticsEngine::Level Level,
557 ArrayRef<CharSourceRange> Ranges) {
558 if (PLoc.isInvalid()) {
559 // At least print the file name if available:
560 FileID FID = SM.getFileID(Loc);
561 if (!FID.isInvalid()) {
562 const FileEntry* FE = SM.getFileEntryForID(FID);
563 if (FE && FE->getName()) {
564 OS << FE->getName();
565 if (FE->getDevice() == 0 && FE->getInode() == 0
566 && FE->getFileMode() == 0) {
567 // in PCH is a guess, but a good one:
568 OS << " (in PCH)";
569 }
570 OS << ": ";
571 }
572 }
573 return;
574 }
575 unsigned LineNo = PLoc.getLine();
576
577 if (!DiagOpts.ShowLocation)
578 return;
579
580 if (DiagOpts.ShowColors)
581 OS.changeColor(savedColor, true);
582
583 OS << PLoc.getFilename();
584 switch (DiagOpts.Format) {
585 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
586 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
587 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
588 }
589
590 if (DiagOpts.ShowColumn)
591 // Compute the column number.
592 if (unsigned ColNo = PLoc.getColumn()) {
593 if (DiagOpts.Format == DiagnosticOptions::Msvc) {
594 OS << ',';
595 ColNo--;
596 } else
597 OS << ':';
598 OS << ColNo;
599 }
600 switch (DiagOpts.Format) {
601 case DiagnosticOptions::Clang:
602 case DiagnosticOptions::Vi: OS << ':'; break;
603 case DiagnosticOptions::Msvc: OS << ") : "; break;
604 }
605
606 if (DiagOpts.ShowSourceRanges && !Ranges.empty()) {
607 FileID CaretFileID =
608 SM.getFileID(SM.getExpansionLoc(Loc));
609 bool PrintedRange = false;
610
611 for (ArrayRef<CharSourceRange>::const_iterator RI = Ranges.begin(),
612 RE = Ranges.end();
613 RI != RE; ++RI) {
614 // Ignore invalid ranges.
615 if (!RI->isValid()) continue;
616
617 SourceLocation B = SM.getExpansionLoc(RI->getBegin());
618 SourceLocation E = SM.getExpansionLoc(RI->getEnd());
619
620 // If the End location and the start location are the same and are a
621 // macro location, then the range was something that came from a
622 // macro expansion or _Pragma. If this is an object-like macro, the
623 // best we can do is to highlight the range. If this is a
624 // function-like macro, we'd also like to highlight the arguments.
625 if (B == E && RI->getEnd().isMacroID())
626 E = SM.getExpansionRange(RI->getEnd()).second;
627
628 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
629 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
630
631 // If the start or end of the range is in another file, just discard
632 // it.
633 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
634 continue;
635
636 // Add in the length of the token, so that we cover multi-char
637 // tokens.
638 unsigned TokSize = 0;
639 if (RI->isTokenRange())
640 TokSize = Lexer::MeasureTokenLength(E, SM, LangOpts);
641
642 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
643 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
644 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
645 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
646 << '}';
647 PrintedRange = true;
648 }
649
650 if (PrintedRange)
651 OS << ':';
652 }
653 OS << ' ';
654}
655
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000656/// \brief Emit the caret and underlining text.
657///
658/// Walks up the macro expansion stack printing the code snippet, caret,
659/// underlines and FixItHint display as appropriate at each level. Walk is
660/// accomplished by calling itself recursively.
661///
662/// FIXME: Remove macro expansion from this routine, it shouldn't be tied to
663/// caret diagnostics.
664/// FIXME: Break up massive function into logical units.
665///
666/// \param Loc The location for this caret.
667/// \param Ranges The underlined ranges for this code snippet.
668/// \param Hints The FixIt hints active for this diagnostic.
669/// \param MacroSkipEnd The depth to stop skipping macro expansions.
670/// \param OnMacroInst The current depth of the macro expansion stack.
Chandler Carruth7531f572011-10-15 23:54:09 +0000671void TextDiagnostic::emitCaret(SourceLocation Loc,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000672 SmallVectorImpl<CharSourceRange>& Ranges,
673 ArrayRef<FixItHint> Hints,
674 unsigned &MacroDepth,
675 unsigned OnMacroInst) {
676 assert(!Loc.isInvalid() && "must have a valid source location here");
677
678 // If this is a file source location, directly emit the source snippet and
679 // caret line. Also record the macro depth reached.
680 if (Loc.isFileID()) {
681 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
682 MacroDepth = OnMacroInst;
Chandler Carruth7531f572011-10-15 23:54:09 +0000683 emitSnippetAndCaret(Loc, Ranges, Hints);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000684 return;
685 }
686 // Otherwise recurse through each macro expansion layer.
687
688 // When processing macros, skip over the expansions leading up to
689 // a macro argument, and trace the argument's expansion stack instead.
690 Loc = skipToMacroArgExpansion(SM, Loc);
691
692 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
693
694 // FIXME: Map ranges?
Chandler Carruth7531f572011-10-15 23:54:09 +0000695 emitCaret(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000696
697 // Map the location.
698 Loc = getImmediateMacroCalleeLoc(SM, Loc);
699
700 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
701 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
702 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
703 DiagOpts.MacroBacktraceLimit % 2;
704 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
705 }
706
707 // Whether to suppress printing this macro expansion.
708 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
709 OnMacroInst < MacroSkipEnd);
710
711 // Map the ranges.
712 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
713 E = Ranges.end();
714 I != E; ++I) {
715 SourceLocation Start = I->getBegin(), End = I->getEnd();
716 if (Start.isMacroID())
717 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
718 if (End.isMacroID())
719 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
720 }
721
722 if (!Suppressed) {
723 // Don't print recursive expansion notes from an expansion note.
724 Loc = SM.getSpellingLoc(Loc);
725
726 // Get the pretty name, according to #line directives etc.
727 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
728 if (PLoc.isInvalid())
729 return;
730
731 // If this diagnostic is not in the main file, print out the
732 // "included from" lines.
733 emitIncludeStack(PLoc.getIncludeLoc(), DiagnosticsEngine::Note);
734
735 if (DiagOpts.ShowLocation) {
736 // Emit the file/line/column that this expansion came from.
737 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
738 if (DiagOpts.ShowColumn)
739 OS << PLoc.getColumn() << ':';
740 OS << ' ';
741 }
742 OS << "note: expanded from:\n";
743
Chandler Carruth7531f572011-10-15 23:54:09 +0000744 emitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000745 return;
746 }
747
748 if (OnMacroInst == MacroSkipStart) {
749 // Tell the user that we've skipped contexts.
750 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
751 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
752 "all)\n";
753 }
754}
755
756/// \brief Emit a code snippet and caret line.
757///
758/// This routine emits a single line's code snippet and caret line..
759///
760/// \param Loc The location for the caret.
761/// \param Ranges The underlined ranges for this code snippet.
762/// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruth7531f572011-10-15 23:54:09 +0000763void TextDiagnostic::emitSnippetAndCaret(
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000764 SourceLocation Loc,
765 SmallVectorImpl<CharSourceRange>& Ranges,
766 ArrayRef<FixItHint> Hints) {
767 assert(!Loc.isInvalid() && "must have a valid source location here");
768 assert(Loc.isFileID() && "must have a file location here");
769
770 // Decompose the location into a FID/Offset pair.
771 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
772 FileID FID = LocInfo.first;
773 unsigned FileOffset = LocInfo.second;
774
775 // Get information about the buffer it points into.
776 bool Invalid = false;
777 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
778 if (Invalid)
779 return;
780
781 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
782 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
783 unsigned CaretEndColNo
784 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
785
786 // Rewind from the current position to the start of the line.
787 const char *TokPtr = BufStart+FileOffset;
788 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
789
790
791 // Compute the line end. Scan forward from the error position to the end of
792 // the line.
793 const char *LineEnd = TokPtr;
794 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
795 ++LineEnd;
796
797 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
798 // the source line length as currently being computed. See
799 // test/Misc/message-length.c.
800 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
801
802 // Copy the line of code into an std::string for ease of manipulation.
803 std::string SourceLine(LineStart, LineEnd);
804
805 // Create a line for the caret that is filled with spaces that is the same
806 // length as the line of source code.
807 std::string CaretLine(LineEnd-LineStart, ' ');
808
809 // Highlight all of the characters covered by Ranges with ~ characters.
810 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
811 E = Ranges.end();
812 I != E; ++I)
Chandler Carruth7531f572011-10-15 23:54:09 +0000813 highlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000814
815 // Next, insert the caret itself.
816 if (ColNo-1 < CaretLine.size())
817 CaretLine[ColNo-1] = '^';
818 else
819 CaretLine.push_back('^');
820
Chandler Carruth7531f572011-10-15 23:54:09 +0000821 expandTabs(SourceLine, CaretLine);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000822
823 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
824 // to produce easily machine parsable output. Add a space before the
825 // source line and the caret to make it trivial to tell the main diagnostic
826 // line from what the user is intended to see.
827 if (DiagOpts.ShowSourceRanges) {
828 SourceLine = ' ' + SourceLine;
829 CaretLine = ' ' + CaretLine;
830 }
831
Chandler Carruth7531f572011-10-15 23:54:09 +0000832 std::string FixItInsertionLine = buildFixItInsertionLine(LineNo,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000833 LineStart, LineEnd,
834 Hints);
835
836 // If the source line is too long for our terminal, select only the
837 // "interesting" source region within that line.
838 unsigned Columns = DiagOpts.MessageLength;
839 if (Columns && SourceLine.size() > Columns)
Chandler Carruth7531f572011-10-15 23:54:09 +0000840 selectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000841 CaretEndColNo, Columns);
842
843 // Finally, remove any blank spaces from the end of CaretLine.
844 while (CaretLine[CaretLine.size()-1] == ' ')
845 CaretLine.erase(CaretLine.end()-1);
846
847 // Emit what we have computed.
848 OS << SourceLine << '\n';
849
850 if (DiagOpts.ShowColors)
851 OS.changeColor(caretColor, true);
852 OS << CaretLine << '\n';
853 if (DiagOpts.ShowColors)
854 OS.resetColor();
855
856 if (!FixItInsertionLine.empty()) {
857 if (DiagOpts.ShowColors)
858 // Print fixit line in color
859 OS.changeColor(fixitColor, false);
860 if (DiagOpts.ShowSourceRanges)
861 OS << ' ';
862 OS << FixItInsertionLine << '\n';
863 if (DiagOpts.ShowColors)
864 OS.resetColor();
865 }
866
867 // Print out any parseable fixit information requested by the options.
Chandler Carruth7531f572011-10-15 23:54:09 +0000868 emitParseableFixits(Hints);
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000869}
870
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000871/// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
Chandler Carruth7531f572011-10-15 23:54:09 +0000872void TextDiagnostic::highlightRange(const CharSourceRange &R,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000873 unsigned LineNo, FileID FID,
874 const std::string &SourceLine,
875 std::string &CaretLine) {
876 assert(CaretLine.size() == SourceLine.size() &&
877 "Expect a correspondence between source and caret line!");
878 if (!R.isValid()) return;
879
880 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
881 SourceLocation End = SM.getExpansionLoc(R.getEnd());
882
883 // If the End location and the start location are the same and are a macro
884 // location, then the range was something that came from a macro expansion
885 // or _Pragma. If this is an object-like macro, the best we can do is to
886 // highlight the range. If this is a function-like macro, we'd also like to
887 // highlight the arguments.
888 if (Begin == End && R.getEnd().isMacroID())
889 End = SM.getExpansionRange(R.getEnd()).second;
890
891 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
892 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
893 return; // No intersection.
894
895 unsigned EndLineNo = SM.getExpansionLineNumber(End);
896 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
897 return; // No intersection.
898
899 // Compute the column number of the start.
900 unsigned StartColNo = 0;
901 if (StartLineNo == LineNo) {
902 StartColNo = SM.getExpansionColumnNumber(Begin);
903 if (StartColNo) --StartColNo; // Zero base the col #.
904 }
905
906 // Compute the column number of the end.
907 unsigned EndColNo = CaretLine.size();
908 if (EndLineNo == LineNo) {
909 EndColNo = SM.getExpansionColumnNumber(End);
910 if (EndColNo) {
911 --EndColNo; // Zero base the col #.
912
913 // Add in the length of the token, so that we cover multi-char tokens if
914 // this is a token range.
915 if (R.isTokenRange())
916 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
917 } else {
918 EndColNo = CaretLine.size();
919 }
920 }
921
922 assert(StartColNo <= EndColNo && "Invalid range!");
923
924 // Check that a token range does not highlight only whitespace.
925 if (R.isTokenRange()) {
926 // Pick the first non-whitespace column.
927 while (StartColNo < SourceLine.size() &&
928 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
929 ++StartColNo;
930
931 // Pick the last non-whitespace column.
932 if (EndColNo > SourceLine.size())
933 EndColNo = SourceLine.size();
934 while (EndColNo-1 &&
935 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
936 --EndColNo;
937
938 // If the start/end passed each other, then we are trying to highlight a
939 // range that just exists in whitespace, which must be some sort of other
940 // bug.
941 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
942 }
943
944 // Fill the range with ~'s.
945 for (unsigned i = StartColNo; i < EndColNo; ++i)
946 CaretLine[i] = '~';
947}
948
Chandler Carruth7531f572011-10-15 23:54:09 +0000949std::string TextDiagnostic::buildFixItInsertionLine(unsigned LineNo,
Chandler Carruthdb463bb2011-10-15 23:43:53 +0000950 const char *LineStart,
951 const char *LineEnd,
952 ArrayRef<FixItHint> Hints) {
953 std::string FixItInsertionLine;
954 if (Hints.empty() || !DiagOpts.ShowFixits)
955 return FixItInsertionLine;
956
957 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
958 I != E; ++I) {
959 if (!I->CodeToInsert.empty()) {
960 // We have an insertion hint. Determine whether the inserted
961 // code is on the same line as the caret.
962 std::pair<FileID, unsigned> HintLocInfo
963 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
964 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
965 // Insert the new code into the line just below the code
966 // that the user wrote.
967 unsigned HintColNo
968 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
969 unsigned LastColumnModified
970 = HintColNo - 1 + I->CodeToInsert.size();
971 if (LastColumnModified > FixItInsertionLine.size())
972 FixItInsertionLine.resize(LastColumnModified, ' ');
973 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
974 FixItInsertionLine.begin() + HintColNo - 1);
975 } else {
976 FixItInsertionLine.clear();
977 break;
978 }
979 }
980 }
981
982 if (FixItInsertionLine.empty())
983 return FixItInsertionLine;
984
985 // Now that we have the entire fixit line, expand the tabs in it.
986 // Since we don't want to insert spaces in the middle of a word,
987 // find each word and the column it should line up with and insert
988 // spaces until they match.
989 unsigned FixItPos = 0;
990 unsigned LinePos = 0;
991 unsigned TabExpandedCol = 0;
992 unsigned LineLength = LineEnd - LineStart;
993
994 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
995 // Find the next word in the FixIt line.
996 while (FixItPos < FixItInsertionLine.size() &&
997 FixItInsertionLine[FixItPos] == ' ')
998 ++FixItPos;
999 unsigned CharDistance = FixItPos - TabExpandedCol;
1000
1001 // Walk forward in the source line, keeping track of
1002 // the tab-expanded column.
1003 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
1004 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
1005 ++TabExpandedCol;
1006 else
1007 TabExpandedCol =
1008 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
1009
1010 // Adjust the fixit line to match this column.
1011 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
1012 FixItPos = TabExpandedCol;
1013
1014 // Walk to the end of the word.
1015 while (FixItPos < FixItInsertionLine.size() &&
1016 FixItInsertionLine[FixItPos] != ' ')
1017 ++FixItPos;
1018 }
1019
1020 return FixItInsertionLine;
1021}
1022
Chandler Carruth7531f572011-10-15 23:54:09 +00001023void TextDiagnostic::expandTabs(std::string &SourceLine,
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001024 std::string &CaretLine) {
1025 // Scan the source line, looking for tabs. If we find any, manually expand
1026 // them to spaces and update the CaretLine to match.
1027 for (unsigned i = 0; i != SourceLine.size(); ++i) {
1028 if (SourceLine[i] != '\t') continue;
1029
1030 // Replace this tab with at least one space.
1031 SourceLine[i] = ' ';
1032
1033 // Compute the number of spaces we need to insert.
1034 unsigned TabStop = DiagOpts.TabStop;
1035 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
1036 "Invalid -ftabstop value");
1037 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
1038 assert(NumSpaces < TabStop && "Invalid computation of space amt");
1039
1040 // Insert spaces into the SourceLine.
1041 SourceLine.insert(i+1, NumSpaces, ' ');
1042
1043 // Insert spaces or ~'s into CaretLine.
1044 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
1045 }
1046}
1047
Chandler Carruth7531f572011-10-15 23:54:09 +00001048void TextDiagnostic::emitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthdb463bb2011-10-15 23:43:53 +00001049 if (!DiagOpts.ShowParseableFixits)
1050 return;
1051
1052 // We follow FixItRewriter's example in not (yet) handling
1053 // fix-its in macros.
1054 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1055 I != E; ++I) {
1056 if (I->RemoveRange.isInvalid() ||
1057 I->RemoveRange.getBegin().isMacroID() ||
1058 I->RemoveRange.getEnd().isMacroID())
1059 return;
1060 }
1061
1062 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
1063 I != E; ++I) {
1064 SourceLocation BLoc = I->RemoveRange.getBegin();
1065 SourceLocation ELoc = I->RemoveRange.getEnd();
1066
1067 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
1068 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
1069
1070 // Adjust for token ranges.
1071 if (I->RemoveRange.isTokenRange())
1072 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
1073
1074 // We specifically do not do word-wrapping or tab-expansion here,
1075 // because this is supposed to be easy to parse.
1076 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
1077 if (PLoc.isInvalid())
1078 break;
1079
1080 OS << "fix-it:\"";
1081 OS.write_escaped(PLoc.getFilename());
1082 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
1083 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
1084 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
1085 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
1086 << "}:\"";
1087 OS.write_escaped(I->CodeToInsert);
1088 OS << "\"\n";
1089 }
1090}
1091