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