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