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