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