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