blob: 1f6ea30c7d9d016b2f61140ad2d2c9fde9f474a1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- TextDiagnosticPrinter.cpp - Diagnostic Printer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This diagnostic client prints out their diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbare1bd4e62009-03-02 06:16:29 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
Axel Naumann04331162011-01-27 10:55:51 +000015#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "clang/Basic/SourceManager.h"
Daniel Dunbareace8742009-11-04 06:24:30 +000017#include "clang/Frontend/DiagnosticOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/Lex/Lexer.h"
Chris Lattner037fb7f2009-05-05 22:03:18 +000019#include "llvm/Support/MemoryBuffer.h"
Chris Lattnera03a5b52008-11-19 06:56:25 +000020#include "llvm/Support/raw_ostream.h"
David Blaikie548f6c82011-09-23 05:57:42 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattnerf4c83962008-11-19 06:51:40 +000022#include "llvm/ADT/SmallString.h"
Douglas Gregor4b2d3f72009-02-26 21:00:50 +000023#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Chris Lattner5f9e2722011-07-23 10:55:15 +000026static const enum raw_ostream::Colors noteColor =
27 raw_ostream::BLACK;
28static const enum raw_ostream::Colors fixitColor =
29 raw_ostream::GREEN;
30static const enum raw_ostream::Colors caretColor =
31 raw_ostream::GREEN;
32static const enum raw_ostream::Colors warningColor =
33 raw_ostream::MAGENTA;
34static const enum raw_ostream::Colors errorColor = raw_ostream::RED;
35static const enum raw_ostream::Colors fatalColor = raw_ostream::RED;
Daniel Dunbarb96b6702010-02-25 03:23:40 +000036// Used for changing only the bold attribute.
Chris Lattner5f9e2722011-07-23 10:55:15 +000037static const enum raw_ostream::Colors savedColor =
38 raw_ostream::SAVEDCOLOR;
Torok Edwin603fca72009-06-04 07:18:23 +000039
Douglas Gregorfffd93f2009-05-01 21:53:04 +000040/// \brief Number of spaces to indent when word-wrapping.
41const unsigned WordWrapIndentation = 6;
42
Chris Lattner5f9e2722011-07-23 10:55:15 +000043TextDiagnosticPrinter::TextDiagnosticPrinter(raw_ostream &os,
Daniel Dunbaraea36412009-11-11 09:38:24 +000044 const DiagnosticOptions &diags,
45 bool _OwnsOutputStream)
Daniel Dunbareace8742009-11-04 06:24:30 +000046 : OS(os), LangOpts(0), DiagOpts(&diags),
Daniel Dunbaraea36412009-11-11 09:38:24 +000047 LastCaretDiagnosticWasNote(0),
48 OwnsOutputStream(_OwnsOutputStream) {
49}
50
51TextDiagnosticPrinter::~TextDiagnosticPrinter() {
52 if (OwnsOutputStream)
53 delete &OS;
Daniel Dunbareace8742009-11-04 06:24:30 +000054}
55
Chandler Carruth0d6b8932011-08-31 23:59:19 +000056/// \brief Helper to recursivly walk up the include stack and print each layer
57/// on the way back down.
58static void PrintIncludeStackRecursively(raw_ostream &OS,
59 const SourceManager &SM,
60 SourceLocation Loc,
61 bool ShowLocation) {
62 if (Loc.isInvalid())
63 return;
Chris Lattner9dc1f532007-07-20 16:37:10 +000064
Chris Lattnerb9c3f962009-01-27 07:57:44 +000065 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
Douglas Gregorcb7b1e12010-11-12 07:15:47 +000066 if (PLoc.isInvalid())
67 return;
Chris Lattner5ce24c82009-04-21 03:57:54 +000068
Chandler Carruth0d6b8932011-08-31 23:59:19 +000069 // Print out the other include frames first.
70 PrintIncludeStackRecursively(OS, SM, PLoc.getIncludeLoc(), ShowLocation);
71
72 if (ShowLocation)
Chris Lattner5ce24c82009-04-21 03:57:54 +000073 OS << "In file included from " << PLoc.getFilename()
74 << ':' << PLoc.getLine() << ":\n";
75 else
76 OS << "In included file:\n";
Reid Spencer5f016e22007-07-11 17:01:13 +000077}
78
Chandler Carruth0d6b8932011-08-31 23:59:19 +000079/// \brief Prints an include stack when appropriate for a particular diagnostic
80/// level and location.
81///
82/// This routine handles all the logic of suppressing particular include stacks
83/// (such as those for notes) and duplicate include stacks when repeated
84/// warnings occur within the same file. It also handles the logic of
85/// customizing the formatting and display of the include stack.
86///
87/// \param Level The diagnostic level of the message this stack pertains to.
88/// \param Loc The include location of the current file (not the diagnostic
89/// location).
David Blaikied6471f72011-09-25 23:23:43 +000090void TextDiagnosticPrinter::PrintIncludeStack(DiagnosticsEngine::Level Level,
Chandler Carruth0d6b8932011-08-31 23:59:19 +000091 SourceLocation Loc,
92 const SourceManager &SM) {
93 // Skip redundant include stacks altogether.
94 if (LastWarningLoc == Loc)
95 return;
96 LastWarningLoc = Loc;
97
David Blaikied6471f72011-09-25 23:23:43 +000098 if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
Chandler Carruth0d6b8932011-08-31 23:59:19 +000099 return;
100
101 PrintIncludeStackRecursively(OS, SM, Loc, DiagOpts->ShowLocation);
102}
103
Douglas Gregor47f71772009-05-01 23:32:58 +0000104/// \brief When the source code line we want to print is too long for
105/// the terminal, select the "interesting" region.
106static void SelectInterestingSourceRegion(std::string &SourceLine,
107 std::string &CaretLine,
108 std::string &FixItInsertionLine,
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000109 unsigned EndOfCaretToken,
Douglas Gregor47f71772009-05-01 23:32:58 +0000110 unsigned Columns) {
Douglas Gregorce487ef2010-04-16 00:23:51 +0000111 unsigned MaxSize = std::max(SourceLine.size(),
112 std::max(CaretLine.size(),
113 FixItInsertionLine.size()));
114 if (MaxSize > SourceLine.size())
115 SourceLine.resize(MaxSize, ' ');
116 if (MaxSize > CaretLine.size())
117 CaretLine.resize(MaxSize, ' ');
118 if (!FixItInsertionLine.empty() && MaxSize > FixItInsertionLine.size())
119 FixItInsertionLine.resize(MaxSize, ' ');
120
Douglas Gregor47f71772009-05-01 23:32:58 +0000121 // Find the slice that we need to display the full caret line
122 // correctly.
123 unsigned CaretStart = 0, CaretEnd = CaretLine.size();
124 for (; CaretStart != CaretEnd; ++CaretStart)
125 if (!isspace(CaretLine[CaretStart]))
126 break;
127
128 for (; CaretEnd != CaretStart; --CaretEnd)
129 if (!isspace(CaretLine[CaretEnd - 1]))
130 break;
Douglas Gregorcfe1f9d2009-05-04 06:27:32 +0000131
132 // Make sure we don't chop the string shorter than the caret token
133 // itself.
134 if (CaretEnd < EndOfCaretToken)
135 CaretEnd = EndOfCaretToken;
136
Douglas Gregor844da342009-05-03 04:33:32 +0000137 // If we have a fix-it line, make sure the slice includes all of the
138 // fix-it information.
139 if (!FixItInsertionLine.empty()) {
140 unsigned FixItStart = 0, FixItEnd = FixItInsertionLine.size();
141 for (; FixItStart != FixItEnd; ++FixItStart)
142 if (!isspace(FixItInsertionLine[FixItStart]))
143 break;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000144
Douglas Gregor844da342009-05-03 04:33:32 +0000145 for (; FixItEnd != FixItStart; --FixItEnd)
146 if (!isspace(FixItInsertionLine[FixItEnd - 1]))
147 break;
148
149 if (FixItStart < CaretStart)
150 CaretStart = FixItStart;
151 if (FixItEnd > CaretEnd)
152 CaretEnd = FixItEnd;
153 }
154
Douglas Gregor47f71772009-05-01 23:32:58 +0000155 // CaretLine[CaretStart, CaretEnd) contains all of the interesting
156 // parts of the caret line. While this slice is smaller than the
157 // number of columns we have, try to grow the slice to encompass
158 // more context.
159
160 // If the end of the interesting region comes before we run out of
161 // space in the terminal, start at the beginning of the line.
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000162 if (Columns > 3 && CaretEnd < Columns - 3)
Douglas Gregor47f71772009-05-01 23:32:58 +0000163 CaretStart = 0;
164
Douglas Gregorc95bd4d2009-05-15 18:05:24 +0000165 unsigned TargetColumns = Columns;
166 if (TargetColumns > 8)
167 TargetColumns -= 8; // Give us extra room for the ellipses.
Douglas Gregor47f71772009-05-01 23:32:58 +0000168 unsigned SourceLength = SourceLine.size();
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000169 while ((CaretEnd - CaretStart) < TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000170 bool ExpandedRegion = false;
171 // Move the start of the interesting region left until we've
172 // pulled in something else interesting.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000173 if (CaretStart == 1)
174 CaretStart = 0;
175 else if (CaretStart > 1) {
176 unsigned NewStart = CaretStart - 1;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000177
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000178 // Skip over any whitespace we see here; we're looking for
179 // another bit of interesting text.
180 while (NewStart && isspace(SourceLine[NewStart]))
181 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000182
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000183 // Skip over this bit of "interesting" text.
184 while (NewStart && !isspace(SourceLine[NewStart]))
185 --NewStart;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000186
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000187 // Move up to the non-whitespace character we just saw.
188 if (NewStart)
189 ++NewStart;
Douglas Gregor47f71772009-05-01 23:32:58 +0000190
191 // If we're still within our limit, update the starting
192 // position within the source/caret line.
Douglas Gregor2fb3ea32009-05-04 06:45:38 +0000193 if (CaretEnd - NewStart <= TargetColumns) {
Douglas Gregor47f71772009-05-01 23:32:58 +0000194 CaretStart = NewStart;
195 ExpandedRegion = true;
196 }
197 }
198
199 // Move the end of the interesting region right until we've
200 // pulled in something else interesting.
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000201 if (CaretEnd != SourceLength) {
Daniel Dunbar06d10722009-10-19 09:11:21 +0000202 assert(CaretEnd < SourceLength && "Unexpected caret position!");
Douglas Gregor47f71772009-05-01 23:32:58 +0000203 unsigned NewEnd = CaretEnd;
204
205 // Skip over any whitespace we see here; we're looking for
206 // another bit of interesting text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000207 while (NewEnd != SourceLength && isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000208 ++NewEnd;
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000209
Douglas Gregor47f71772009-05-01 23:32:58 +0000210 // Skip over this bit of "interesting" text.
Douglas Gregor1f0eb562009-05-18 22:09:16 +0000211 while (NewEnd != SourceLength && !isspace(SourceLine[NewEnd - 1]))
Douglas Gregor47f71772009-05-01 23:32:58 +0000212 ++NewEnd;
213
214 if (NewEnd - CaretStart <= TargetColumns) {
215 CaretEnd = NewEnd;
216 ExpandedRegion = true;
217 }
Douglas Gregor47f71772009-05-01 23:32:58 +0000218 }
Daniel Dunbar1ef29d22009-05-03 23:04:40 +0000219
220 if (!ExpandedRegion)
221 break;
Douglas Gregor47f71772009-05-01 23:32:58 +0000222 }
223
224 // [CaretStart, CaretEnd) is the slice we want. Update the various
225 // output lines to show only this slice, with two-space padding
226 // before the lines so that it looks nicer.
Douglas Gregor7d101f62009-05-03 04:12:51 +0000227 if (CaretEnd < SourceLine.size())
228 SourceLine.replace(CaretEnd, std::string::npos, "...");
Douglas Gregor2167de42009-05-03 15:24:25 +0000229 if (CaretEnd < CaretLine.size())
230 CaretLine.erase(CaretEnd, std::string::npos);
Douglas Gregor47f71772009-05-01 23:32:58 +0000231 if (FixItInsertionLine.size() > CaretEnd)
232 FixItInsertionLine.erase(CaretEnd, std::string::npos);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +0000233
Douglas Gregor47f71772009-05-01 23:32:58 +0000234 if (CaretStart > 2) {
Douglas Gregor7d101f62009-05-03 04:12:51 +0000235 SourceLine.replace(0, CaretStart, " ...");
236 CaretLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000237 if (FixItInsertionLine.size() >= CaretStart)
Douglas Gregor7d101f62009-05-03 04:12:51 +0000238 FixItInsertionLine.replace(0, CaretStart, " ");
Douglas Gregor47f71772009-05-01 23:32:58 +0000239 }
240}
241
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000242/// Look through spelling locations for a macro argument expansion, and
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000243/// if found skip to it so that we can trace the argument rather than the macros
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000244/// in which that argument is used. If no macro argument expansion is found,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000245/// don't skip anything and return the starting location.
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000246static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000247 SourceLocation StartLoc) {
248 for (SourceLocation L = StartLoc; L.isMacroID();
249 L = SM.getImmediateSpellingLoc(L)) {
Chandler Carruth96d35892011-07-26 03:03:00 +0000250 if (SM.isMacroArgExpansion(L))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000251 return L;
252 }
253
254 // Otherwise just return initial location, there's nothing to skip.
255 return StartLoc;
256}
257
258/// Gets the location of the immediate macro caller, one level up the stack
259/// toward the initial macro typed into the source.
260static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
261 SourceLocation Loc) {
262 if (!Loc.isMacroID()) return Loc;
263
264 // When we have the location of (part of) an expanded parameter, its spelling
265 // location points to the argument as typed into the macro call, and
266 // therefore is used to locate the macro caller.
Chandler Carruth96d35892011-07-26 03:03:00 +0000267 if (SM.isMacroArgExpansion(Loc))
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000268 return SM.getImmediateSpellingLoc(Loc);
269
270 // Otherwise, the caller of the macro is located where this macro is
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000271 // expanded (while the spelling is part of the macro definition).
Chandler Carruth999f7392011-07-25 20:52:21 +0000272 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000273}
274
275/// Gets the location of the immediate macro callee, one level down the stack
276/// toward the leaf macro.
277static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
278 SourceLocation Loc) {
279 if (!Loc.isMacroID()) return Loc;
280
281 // When we have the location of (part of) an expanded parameter, its
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000282 // expansion location points to the unexpanded paramater reference within
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000283 // the macro definition (or callee).
Chandler Carruth96d35892011-07-26 03:03:00 +0000284 if (SM.isMacroArgExpansion(Loc))
Chandler Carruth999f7392011-07-25 20:52:21 +0000285 return SM.getImmediateExpansionRange(Loc).first;
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000286
287 // Otherwise, the callee of the macro is located where this location was
288 // spelled inside the macro definition.
289 return SM.getImmediateSpellingLoc(Loc);
290}
291
Chandler Carruth50c909b2011-08-31 23:59:23 +0000292namespace {
293
Chandler Carruth18fc0022011-09-25 22:54:56 +0000294/// \brief Class to encapsulate the logic for formatting and printing a textual
295/// diagnostic message.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000296///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000297/// This class provides an interface for building and emitting a textual
298/// diagnostic, including all of the macro backtraces, caret diagnostics, FixIt
299/// Hints, and code snippets. In the presence of macros this involves
300/// a recursive process, synthesizing notes for each macro expansion.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000301///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000302/// The purpose of this class is to isolate the implementation of printing
303/// beautiful text diagnostics from any particular interfaces. The Clang
304/// DiagnosticClient is implemented through this class as is diagnostic
305/// printing coming out of libclang.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000306///
Chandler Carruth18fc0022011-09-25 22:54:56 +0000307/// A brief worklist:
308/// FIXME: Sink the printing of the diagnostic message itself into this class.
309/// FIXME: Sink the printing of the include stack into this class.
310/// FIXME: Remove the TextDiagnosticPrinter as an input.
311/// FIXME: Sink the recursive printing of template instantiations into this
312/// class.
313class TextDiagnostic {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000314 TextDiagnosticPrinter &Printer;
315 raw_ostream &OS;
316 const SourceManager &SM;
317 const LangOptions &LangOpts;
318 const DiagnosticOptions &DiagOpts;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000319
320public:
Chandler Carruth18fc0022011-09-25 22:54:56 +0000321 TextDiagnostic(TextDiagnosticPrinter &Printer,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000322 raw_ostream &OS,
323 const SourceManager &SM,
324 const LangOptions &LangOpts,
Chandler Carruth8be5c152011-09-25 22:31:58 +0000325 const DiagnosticOptions &DiagOpts)
326 : Printer(Printer), OS(OS), SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts) {
Chandler Carruth50c909b2011-08-31 23:59:23 +0000327 }
328
329 /// \brief Emit the caret diagnostic text.
330 ///
331 /// Walks up the macro expansion stack printing the code snippet, caret,
332 /// underlines and FixItHint display as appropriate at each level. Walk is
333 /// accomplished by calling itself recursively.
334 ///
Chandler Carruth50c909b2011-08-31 23:59:23 +0000335 /// FIXME: Break up massive function into logical units.
336 ///
337 /// \param Loc The location for this caret.
338 /// \param Ranges The underlined ranges for this code snippet.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000339 /// \param Hints The FixIt hints active for this diagnostic.
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000340 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000341 /// \param OnMacroInst The current depth of the macro expansion stack.
342 void Emit(SourceLocation Loc,
Chandler Carruth5182a182011-09-07 01:47:09 +0000343 SmallVectorImpl<CharSourceRange>& Ranges,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000344 ArrayRef<FixItHint> Hints,
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000345 unsigned &MacroDepth,
Chandler Carruth50c909b2011-08-31 23:59:23 +0000346 unsigned OnMacroInst = 0) {
347 assert(!Loc.isInvalid() && "must have a valid source location here");
348
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000349 // If this is a file source location, directly emit the source snippet and
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000350 // caret line. Also record the macro depth reached.
351 if (Loc.isFileID()) {
352 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
353 MacroDepth = OnMacroInst;
354 EmitSnippetAndCaret(Loc, Ranges, Hints);
355 return;
356 }
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000357 // Otherwise recurse through each macro expansion layer.
Chandler Carruth50c909b2011-08-31 23:59:23 +0000358
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000359 // When processing macros, skip over the expansions leading up to
360 // a macro argument, and trace the argument's expansion stack instead.
361 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000362
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000363 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000364
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000365 // FIXME: Map ranges?
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000366 Emit(OneLevelUp, Ranges, Hints, MacroDepth, OnMacroInst + 1);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000367
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000368 // Map the location.
369 Loc = getImmediateMacroCalleeLoc(SM, Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000370
Chandler Carruthb9c398b2011-09-25 22:27:52 +0000371 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
372 if (MacroDepth > DiagOpts.MacroBacktraceLimit) {
373 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
374 DiagOpts.MacroBacktraceLimit % 2;
375 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
376 }
377
378 // Whether to suppress printing this macro expansion.
379 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
380 OnMacroInst < MacroSkipEnd);
381
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000382 // Map the ranges.
383 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
384 E = Ranges.end();
385 I != E; ++I) {
386 SourceLocation Start = I->getBegin(), End = I->getEnd();
387 if (Start.isMacroID())
388 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
389 if (End.isMacroID())
390 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
391 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000392
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000393 if (!Suppressed) {
394 // Don't print recursive expansion notes from an expansion note.
395 Loc = SM.getSpellingLoc(Loc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000396
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000397 // Get the pretty name, according to #line directives etc.
398 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
399 if (PLoc.isInvalid())
Chandler Carruth50c909b2011-08-31 23:59:23 +0000400 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000401
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000402 // If this diagnostic is not in the main file, print out the
403 // "included from" lines.
David Blaikied6471f72011-09-25 23:23:43 +0000404 Printer.PrintIncludeStack(DiagnosticsEngine::Note, PLoc.getIncludeLoc(),
405 SM);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000406
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000407 if (DiagOpts.ShowLocation) {
408 // Emit the file/line/column that this expansion came from.
409 OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':';
410 if (DiagOpts.ShowColumn)
411 OS << PLoc.getColumn() << ':';
412 OS << ' ';
413 }
414 OS << "note: expanded from:\n";
415
416 EmitSnippetAndCaret(Loc, Ranges, ArrayRef<FixItHint>());
Chandler Carruth50c909b2011-08-31 23:59:23 +0000417 return;
418 }
419
Chandler Carrutha02a8a92011-09-25 06:59:38 +0000420 if (OnMacroInst == MacroSkipStart) {
421 // Tell the user that we've skipped contexts.
422 OS << "note: (skipping " << (MacroSkipEnd - MacroSkipStart)
423 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to see "
424 "all)\n";
425 }
426 }
427
428 /// \brief Emit a code snippet and caret line.
429 ///
430 /// This routine emits a single line's code snippet and caret line..
431 ///
432 /// \param Loc The location for the caret.
433 /// \param Ranges The underlined ranges for this code snippet.
434 /// \param Hints The FixIt hints active for this diagnostic.
435 void EmitSnippetAndCaret(SourceLocation Loc,
436 SmallVectorImpl<CharSourceRange>& Ranges,
437 ArrayRef<FixItHint> Hints) {
438 assert(!Loc.isInvalid() && "must have a valid source location here");
439 assert(Loc.isFileID() && "must have a file location here");
440
Chandler Carruth50c909b2011-08-31 23:59:23 +0000441 // Decompose the location into a FID/Offset pair.
442 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
443 FileID FID = LocInfo.first;
444 unsigned FileOffset = LocInfo.second;
445
446 // Get information about the buffer it points into.
447 bool Invalid = false;
448 const char *BufStart = SM.getBufferData(FID, &Invalid).data();
449 if (Invalid)
450 return;
451
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000452 unsigned LineNo = SM.getLineNumber(FID, FileOffset);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000453 unsigned ColNo = SM.getColumnNumber(FID, FileOffset);
454 unsigned CaretEndColNo
455 = ColNo + Lexer::MeasureTokenLength(Loc, SM, LangOpts);
456
457 // Rewind from the current position to the start of the line.
458 const char *TokPtr = BufStart+FileOffset;
459 const char *LineStart = TokPtr-ColNo+1; // Column # is 1-based.
460
461
462 // Compute the line end. Scan forward from the error position to the end of
463 // the line.
464 const char *LineEnd = TokPtr;
465 while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0')
466 ++LineEnd;
467
468 // FIXME: This shouldn't be necessary, but the CaretEndColNo can extend past
469 // the source line length as currently being computed. See
470 // test/Misc/message-length.c.
471 CaretEndColNo = std::min(CaretEndColNo, unsigned(LineEnd - LineStart));
472
473 // Copy the line of code into an std::string for ease of manipulation.
474 std::string SourceLine(LineStart, LineEnd);
475
476 // Create a line for the caret that is filled with spaces that is the same
477 // length as the line of source code.
478 std::string CaretLine(LineEnd-LineStart, ' ');
479
480 // Highlight all of the characters covered by Ranges with ~ characters.
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000481 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
482 E = Ranges.end();
483 I != E; ++I)
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000484 HighlightRange(*I, LineNo, FID, SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000485
486 // Next, insert the caret itself.
487 if (ColNo-1 < CaretLine.size())
488 CaretLine[ColNo-1] = '^';
489 else
490 CaretLine.push_back('^');
491
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000492 ExpandTabs(SourceLine, CaretLine);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000493
494 // If we are in -fdiagnostics-print-source-range-info mode, we are trying
495 // to produce easily machine parsable output. Add a space before the
496 // source line and the caret to make it trivial to tell the main diagnostic
497 // line from what the user is intended to see.
498 if (DiagOpts.ShowSourceRanges) {
499 SourceLine = ' ' + SourceLine;
500 CaretLine = ' ' + CaretLine;
501 }
502
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000503 std::string FixItInsertionLine = BuildFixItInsertionLine(LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000504 LineStart, LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000505 Hints);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000506
507 // If the source line is too long for our terminal, select only the
508 // "interesting" source region within that line.
Chandler Carruth8be5c152011-09-25 22:31:58 +0000509 unsigned Columns = DiagOpts.MessageLength;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000510 if (Columns && SourceLine.size() > Columns)
511 SelectInterestingSourceRegion(SourceLine, CaretLine, FixItInsertionLine,
512 CaretEndColNo, Columns);
513
514 // Finally, remove any blank spaces from the end of CaretLine.
515 while (CaretLine[CaretLine.size()-1] == ' ')
516 CaretLine.erase(CaretLine.end()-1);
517
518 // Emit what we have computed.
519 OS << SourceLine << '\n';
520
521 if (DiagOpts.ShowColors)
522 OS.changeColor(caretColor, true);
523 OS << CaretLine << '\n';
524 if (DiagOpts.ShowColors)
525 OS.resetColor();
526
527 if (!FixItInsertionLine.empty()) {
528 if (DiagOpts.ShowColors)
529 // Print fixit line in color
530 OS.changeColor(fixitColor, false);
531 if (DiagOpts.ShowSourceRanges)
532 OS << ' ';
533 OS << FixItInsertionLine << '\n';
534 if (DiagOpts.ShowColors)
535 OS.resetColor();
536 }
537
Chandler Carruthcca61582011-09-02 06:30:30 +0000538 // Print out any parseable fixit information requested by the options.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000539 EmitParseableFixits(Hints);
Chandler Carruthcca61582011-09-02 06:30:30 +0000540 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000541
Chandler Carruthcca61582011-09-02 06:30:30 +0000542private:
Chandler Carruth6c57cce2011-09-07 07:02:31 +0000543 /// \brief Highlight a SourceRange (with ~'s) for any characters on LineNo.
544 void HighlightRange(const CharSourceRange &R,
545 unsigned LineNo, FileID FID,
546 const std::string &SourceLine,
547 std::string &CaretLine) {
548 assert(CaretLine.size() == SourceLine.size() &&
549 "Expect a correspondence between source and caret line!");
550 if (!R.isValid()) return;
551
552 SourceLocation Begin = SM.getExpansionLoc(R.getBegin());
553 SourceLocation End = SM.getExpansionLoc(R.getEnd());
554
555 // If the End location and the start location are the same and are a macro
556 // location, then the range was something that came from a macro expansion
557 // or _Pragma. If this is an object-like macro, the best we can do is to
558 // highlight the range. If this is a function-like macro, we'd also like to
559 // highlight the arguments.
560 if (Begin == End && R.getEnd().isMacroID())
561 End = SM.getExpansionRange(R.getEnd()).second;
562
563 unsigned StartLineNo = SM.getExpansionLineNumber(Begin);
564 if (StartLineNo > LineNo || SM.getFileID(Begin) != FID)
565 return; // No intersection.
566
567 unsigned EndLineNo = SM.getExpansionLineNumber(End);
568 if (EndLineNo < LineNo || SM.getFileID(End) != FID)
569 return; // No intersection.
570
571 // Compute the column number of the start.
572 unsigned StartColNo = 0;
573 if (StartLineNo == LineNo) {
574 StartColNo = SM.getExpansionColumnNumber(Begin);
575 if (StartColNo) --StartColNo; // Zero base the col #.
576 }
577
578 // Compute the column number of the end.
579 unsigned EndColNo = CaretLine.size();
580 if (EndLineNo == LineNo) {
581 EndColNo = SM.getExpansionColumnNumber(End);
582 if (EndColNo) {
583 --EndColNo; // Zero base the col #.
584
585 // Add in the length of the token, so that we cover multi-char tokens if
586 // this is a token range.
587 if (R.isTokenRange())
588 EndColNo += Lexer::MeasureTokenLength(End, SM, LangOpts);
589 } else {
590 EndColNo = CaretLine.size();
591 }
592 }
593
594 assert(StartColNo <= EndColNo && "Invalid range!");
595
596 // Check that a token range does not highlight only whitespace.
597 if (R.isTokenRange()) {
598 // Pick the first non-whitespace column.
599 while (StartColNo < SourceLine.size() &&
600 (SourceLine[StartColNo] == ' ' || SourceLine[StartColNo] == '\t'))
601 ++StartColNo;
602
603 // Pick the last non-whitespace column.
604 if (EndColNo > SourceLine.size())
605 EndColNo = SourceLine.size();
606 while (EndColNo-1 &&
607 (SourceLine[EndColNo-1] == ' ' || SourceLine[EndColNo-1] == '\t'))
608 --EndColNo;
609
610 // If the start/end passed each other, then we are trying to highlight a
611 // range that just exists in whitespace, which must be some sort of other
612 // bug.
613 assert(StartColNo <= EndColNo && "Trying to highlight whitespace??");
614 }
615
616 // Fill the range with ~'s.
617 for (unsigned i = StartColNo; i < EndColNo; ++i)
618 CaretLine[i] = '~';
619 }
620
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000621 std::string BuildFixItInsertionLine(unsigned LineNo,
Chandler Carruth682630c2011-09-06 22:01:04 +0000622 const char *LineStart,
623 const char *LineEnd,
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000624 ArrayRef<FixItHint> Hints) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000625 std::string FixItInsertionLine;
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000626 if (Hints.empty() || !DiagOpts.ShowFixits)
Chandler Carruth682630c2011-09-06 22:01:04 +0000627 return FixItInsertionLine;
628
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000629 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
630 I != E; ++I) {
631 if (!I->CodeToInsert.empty()) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000632 // We have an insertion hint. Determine whether the inserted
633 // code is on the same line as the caret.
634 std::pair<FileID, unsigned> HintLocInfo
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000635 = SM.getDecomposedExpansionLoc(I->RemoveRange.getBegin());
Chandler Carruth0580e7d2011-09-07 05:01:10 +0000636 if (LineNo == SM.getLineNumber(HintLocInfo.first, HintLocInfo.second)) {
Chandler Carruth682630c2011-09-06 22:01:04 +0000637 // Insert the new code into the line just below the code
638 // that the user wrote.
639 unsigned HintColNo
640 = SM.getColumnNumber(HintLocInfo.first, HintLocInfo.second);
641 unsigned LastColumnModified
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000642 = HintColNo - 1 + I->CodeToInsert.size();
Chandler Carruth682630c2011-09-06 22:01:04 +0000643 if (LastColumnModified > FixItInsertionLine.size())
644 FixItInsertionLine.resize(LastColumnModified, ' ');
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000645 std::copy(I->CodeToInsert.begin(), I->CodeToInsert.end(),
Chandler Carruth682630c2011-09-06 22:01:04 +0000646 FixItInsertionLine.begin() + HintColNo - 1);
647 } else {
648 FixItInsertionLine.clear();
649 break;
650 }
651 }
652 }
653
654 if (FixItInsertionLine.empty())
655 return FixItInsertionLine;
656
657 // Now that we have the entire fixit line, expand the tabs in it.
658 // Since we don't want to insert spaces in the middle of a word,
659 // find each word and the column it should line up with and insert
660 // spaces until they match.
661 unsigned FixItPos = 0;
662 unsigned LinePos = 0;
663 unsigned TabExpandedCol = 0;
664 unsigned LineLength = LineEnd - LineStart;
665
666 while (FixItPos < FixItInsertionLine.size() && LinePos < LineLength) {
667 // Find the next word in the FixIt line.
668 while (FixItPos < FixItInsertionLine.size() &&
669 FixItInsertionLine[FixItPos] == ' ')
670 ++FixItPos;
671 unsigned CharDistance = FixItPos - TabExpandedCol;
672
673 // Walk forward in the source line, keeping track of
674 // the tab-expanded column.
675 for (unsigned I = 0; I < CharDistance; ++I, ++LinePos)
676 if (LinePos >= LineLength || LineStart[LinePos] != '\t')
677 ++TabExpandedCol;
678 else
679 TabExpandedCol =
680 (TabExpandedCol/DiagOpts.TabStop + 1) * DiagOpts.TabStop;
681
682 // Adjust the fixit line to match this column.
683 FixItInsertionLine.insert(FixItPos, TabExpandedCol-FixItPos, ' ');
684 FixItPos = TabExpandedCol;
685
686 // Walk to the end of the word.
687 while (FixItPos < FixItInsertionLine.size() &&
688 FixItInsertionLine[FixItPos] != ' ')
689 ++FixItPos;
690 }
691
692 return FixItInsertionLine;
693 }
694
Chandler Carruthd2156fc2011-09-07 05:36:50 +0000695 void ExpandTabs(std::string &SourceLine, std::string &CaretLine) {
696 // Scan the source line, looking for tabs. If we find any, manually expand
697 // them to spaces and update the CaretLine to match.
698 for (unsigned i = 0; i != SourceLine.size(); ++i) {
699 if (SourceLine[i] != '\t') continue;
700
701 // Replace this tab with at least one space.
702 SourceLine[i] = ' ';
703
704 // Compute the number of spaces we need to insert.
705 unsigned TabStop = DiagOpts.TabStop;
706 assert(0 < TabStop && TabStop <= DiagnosticOptions::MaxTabStop &&
707 "Invalid -ftabstop value");
708 unsigned NumSpaces = ((i+TabStop)/TabStop * TabStop) - (i+1);
709 assert(NumSpaces < TabStop && "Invalid computation of space amt");
710
711 // Insert spaces into the SourceLine.
712 SourceLine.insert(i+1, NumSpaces, ' ');
713
714 // Insert spaces or ~'s into CaretLine.
715 CaretLine.insert(i+1, NumSpaces, CaretLine[i] == '~' ? '~' : ' ');
716 }
717 }
718
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000719 void EmitParseableFixits(ArrayRef<FixItHint> Hints) {
Chandler Carruthcca61582011-09-02 06:30:30 +0000720 if (!DiagOpts.ShowParseableFixits)
721 return;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000722
Chandler Carruthcca61582011-09-02 06:30:30 +0000723 // We follow FixItRewriter's example in not (yet) handling
724 // fix-its in macros.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000725 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
726 I != E; ++I) {
727 if (I->RemoveRange.isInvalid() ||
728 I->RemoveRange.getBegin().isMacroID() ||
729 I->RemoveRange.getEnd().isMacroID())
Chandler Carruthcca61582011-09-02 06:30:30 +0000730 return;
731 }
Chandler Carruth50c909b2011-08-31 23:59:23 +0000732
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000733 for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end();
734 I != E; ++I) {
735 SourceLocation BLoc = I->RemoveRange.getBegin();
736 SourceLocation ELoc = I->RemoveRange.getEnd();
Chandler Carruth50c909b2011-08-31 23:59:23 +0000737
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000738 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
739 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000740
Chandler Carruthcca61582011-09-02 06:30:30 +0000741 // Adjust for token ranges.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000742 if (I->RemoveRange.isTokenRange())
743 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, LangOpts);
Chandler Carruth50c909b2011-08-31 23:59:23 +0000744
Chandler Carruthcca61582011-09-02 06:30:30 +0000745 // We specifically do not do word-wrapping or tab-expansion here,
746 // because this is supposed to be easy to parse.
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000747 PresumedLoc PLoc = SM.getPresumedLoc(BLoc);
Chandler Carruthcca61582011-09-02 06:30:30 +0000748 if (PLoc.isInvalid())
749 break;
Chandler Carruth50c909b2011-08-31 23:59:23 +0000750
Chandler Carruthcca61582011-09-02 06:30:30 +0000751 OS << "fix-it:\"";
Chandler Carruthf15651a2011-09-06 22:34:33 +0000752 OS.write_escaped(PLoc.getFilename());
Chandler Carruthcca61582011-09-02 06:30:30 +0000753 OS << "\":{" << SM.getLineNumber(BInfo.first, BInfo.second)
754 << ':' << SM.getColumnNumber(BInfo.first, BInfo.second)
755 << '-' << SM.getLineNumber(EInfo.first, EInfo.second)
756 << ':' << SM.getColumnNumber(EInfo.first, EInfo.second)
757 << "}:\"";
Chandler Carruth8a7b3f72011-09-06 22:31:44 +0000758 OS.write_escaped(I->CodeToInsert);
Chandler Carruthcca61582011-09-02 06:30:30 +0000759 OS << "\"\n";
Chandler Carruth50c909b2011-08-31 23:59:23 +0000760 }
761 }
762};
763
764} // end namespace
765
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000766/// Get the presumed location of a diagnostic message. This computes the
767/// presumed location for the top of any macro backtrace when present.
768static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
769 SourceLocation Loc) {
770 // This is a condensed form of the algorithm used by EmitCaretDiagnostic to
771 // walk to the top of the macro call stack.
772 while (Loc.isMacroID()) {
Chandler Carruth7e7736a2011-07-14 08:20:31 +0000773 Loc = skipToMacroArgExpansion(SM, Loc);
Chandler Carruthc8d1ecc2011-07-07 23:56:36 +0000774 Loc = getImmediateMacroCallerLoc(SM, Loc);
775 }
776
777 return SM.getPresumedLoc(Loc);
778}
779
Chandler Carruth5770bb72011-09-07 08:05:58 +0000780/// \brief Print out the file/line/column information and include trace.
781///
782/// This method handlen the emission of the diagnostic location information.
783/// This includes extracting as much location information as is present for the
784/// diagnostic and printing it, as well as any include stack or source ranges
785/// necessary.
David Blaikied6471f72011-09-25 23:23:43 +0000786void TextDiagnosticPrinter::EmitDiagnosticLoc(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000787 const Diagnostic &Info,
Chandler Carruth5770bb72011-09-07 08:05:58 +0000788 const SourceManager &SM,
789 PresumedLoc PLoc) {
790 if (PLoc.isInvalid()) {
791 // At least print the file name if available:
792 FileID FID = SM.getFileID(Info.getLocation());
793 if (!FID.isInvalid()) {
794 const FileEntry* FE = SM.getFileEntryForID(FID);
795 if (FE && FE->getName()) {
796 OS << FE->getName();
797 if (FE->getDevice() == 0 && FE->getInode() == 0
798 && FE->getFileMode() == 0) {
799 // in PCH is a guess, but a good one:
800 OS << " (in PCH)";
801 }
802 OS << ": ";
803 }
804 }
805 return;
806 }
807 unsigned LineNo = PLoc.getLine();
808
809 if (!DiagOpts->ShowLocation)
810 return;
811
812 if (DiagOpts->ShowColors)
813 OS.changeColor(savedColor, true);
814
815 OS << PLoc.getFilename();
816 switch (DiagOpts->Format) {
817 case DiagnosticOptions::Clang: OS << ':' << LineNo; break;
818 case DiagnosticOptions::Msvc: OS << '(' << LineNo; break;
819 case DiagnosticOptions::Vi: OS << " +" << LineNo; break;
820 }
821
822 if (DiagOpts->ShowColumn)
823 // Compute the column number.
824 if (unsigned ColNo = PLoc.getColumn()) {
825 if (DiagOpts->Format == DiagnosticOptions::Msvc) {
826 OS << ',';
827 ColNo--;
828 } else
829 OS << ':';
830 OS << ColNo;
831 }
832 switch (DiagOpts->Format) {
833 case DiagnosticOptions::Clang:
834 case DiagnosticOptions::Vi: OS << ':'; break;
835 case DiagnosticOptions::Msvc: OS << ") : "; break;
836 }
837
838 if (DiagOpts->ShowSourceRanges && Info.getNumRanges()) {
839 FileID CaretFileID =
840 SM.getFileID(SM.getExpansionLoc(Info.getLocation()));
841 bool PrintedRange = false;
842
843 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i) {
844 // Ignore invalid ranges.
845 if (!Info.getRange(i).isValid()) continue;
846
847 SourceLocation B = Info.getRange(i).getBegin();
848 SourceLocation E = Info.getRange(i).getEnd();
849 B = SM.getExpansionLoc(B);
850 E = SM.getExpansionLoc(E);
851
852 // If the End location and the start location are the same and are a
853 // macro location, then the range was something that came from a
854 // macro expansion or _Pragma. If this is an object-like macro, the
855 // best we can do is to highlight the range. If this is a
856 // function-like macro, we'd also like to highlight the arguments.
857 if (B == E && Info.getRange(i).getEnd().isMacroID())
858 E = SM.getExpansionRange(Info.getRange(i).getEnd()).second;
859
860 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(B);
861 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(E);
862
863 // If the start or end of the range is in another file, just discard
864 // it.
865 if (BInfo.first != CaretFileID || EInfo.first != CaretFileID)
866 continue;
867
868 // Add in the length of the token, so that we cover multi-char
869 // tokens.
870 unsigned TokSize = 0;
871 if (Info.getRange(i).isTokenRange())
872 TokSize = Lexer::MeasureTokenLength(E, SM, *LangOpts);
873
874 OS << '{' << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
875 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
876 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
877 << (SM.getColumnNumber(EInfo.first, EInfo.second)+TokSize)
878 << '}';
879 PrintedRange = true;
880 }
881
882 if (PrintedRange)
883 OS << ':';
884 }
885 OS << ' ';
886}
887
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +0000888/// \brief Print the diagonstic level to a raw_ostream.
889///
890/// Handles colorizing the level and formatting.
891static void printDiagnosticLevel(raw_ostream &OS,
Chandler Carruth99c4e5b2011-09-25 23:51:01 +0000892 DiagnosticsEngine::Level Level,
893 bool ShowColors) {
894 if (ShowColors) {
895 // Print diagnostic category in bold and color
896 switch (Level) {
897 case DiagnosticsEngine::Ignored:
898 llvm_unreachable("Invalid diagnostic type");
899 case DiagnosticsEngine::Note: OS.changeColor(noteColor, true); break;
900 case DiagnosticsEngine::Warning: OS.changeColor(warningColor, true); break;
901 case DiagnosticsEngine::Error: OS.changeColor(errorColor, true); break;
902 case DiagnosticsEngine::Fatal: OS.changeColor(fatalColor, true); break;
903 }
904 }
905
906 switch (Level) {
907 case DiagnosticsEngine::Ignored: llvm_unreachable("Invalid diagnostic type");
908 case DiagnosticsEngine::Note: OS << "note: "; break;
909 case DiagnosticsEngine::Warning: OS << "warning: "; break;
910 case DiagnosticsEngine::Error: OS << "error: "; break;
911 case DiagnosticsEngine::Fatal: OS << "fatal error: "; break;
912 }
913
914 if (ShowColors)
915 OS.resetColor();
916}
917
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +0000918/// \brief Print the diagnostic name to a raw_ostream.
919///
920/// This prints the diagnostic name to a raw_ostream if it has one. It formats
921/// the name according to the expected diagnostic message formatting:
922/// " [diagnostic_name_here]"
923static void printDiagnosticName(raw_ostream &OS, const Diagnostic &Info) {
Chandler Carruth76145782011-09-26 00:37:30 +0000924 if (!DiagnosticIDs::isBuiltinNote(Info.getID()))
925 OS << " [" << DiagnosticIDs::getName(Info.getID()) << "]";
926}
927
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +0000928/// \brief Print any diagnostic option information to a raw_ostream.
929///
930/// This implements all of the logic for adding diagnostic options to a message
931/// (via OS). Each relevant option is comma separated and all are enclosed in
932/// the standard bracketing: " [...]".
933static void printDiagnosticOptions(raw_ostream &OS,
Chandler Carruth53a529e2011-09-26 00:44:09 +0000934 DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000935 const Diagnostic &Info,
Chandler Carruth53a529e2011-09-26 00:44:09 +0000936 const DiagnosticOptions &DiagOpts) {
Chandler Carruth253d41d2011-09-26 01:21:58 +0000937 bool Started = false;
Chandler Carruth53a529e2011-09-26 00:44:09 +0000938 if (DiagOpts.ShowOptionNames) {
Chandler Carruth253d41d2011-09-26 01:21:58 +0000939 // Handle special cases for non-warnings early.
940 if (Info.getID() == diag::fatal_too_many_errors) {
941 OS << " [-ferror-limit=]";
942 return;
943 }
944
Chandler Carruth53a529e2011-09-26 00:44:09 +0000945 // Was this a warning mapped to an error using -Werror or pragma?
946 if (Level == DiagnosticsEngine::Error &&
947 DiagnosticIDs::isBuiltinWarningOrExtension(Info.getID())) {
948 diag::Mapping mapping = diag::MAP_IGNORE;
949 Info.getDiags()->getDiagnosticLevel(Info.getID(), Info.getLocation(),
950 &mapping);
Chandler Carruth253d41d2011-09-26 01:21:58 +0000951 if (mapping == diag::MAP_WARNING) {
952 OS << " [-Werror";
953 Started = true;
954 }
955 }
956
957 // If the diagnostic is an extension diagnostic and not enabled by default
958 // then it must have been turned on with -pedantic.
959 bool EnabledByDefault;
960 if (DiagnosticIDs::isBuiltinExtensionDiag(Info.getID(),
961 EnabledByDefault) &&
962 !EnabledByDefault) {
963 OS << (Started ? "," : " [") << "-pedantic";
964 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +0000965 }
966
967 StringRef Opt = DiagnosticIDs::getWarningOptionForDiag(Info.getID());
968 if (!Opt.empty()) {
Chandler Carruth253d41d2011-09-26 01:21:58 +0000969 OS << (Started ? "," : " [") << "-W" << Opt;
970 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +0000971 }
972 }
Chandler Carruth53a529e2011-09-26 00:44:09 +0000973
Chandler Carruth253d41d2011-09-26 01:21:58 +0000974 // If the user wants to see category information, include it too.
975 if (DiagOpts.ShowCategories) {
976 unsigned DiagCategory =
977 DiagnosticIDs::getCategoryNumberForDiag(Info.getID());
Chandler Carruth53a529e2011-09-26 00:44:09 +0000978 if (DiagCategory) {
Chandler Carruth253d41d2011-09-26 01:21:58 +0000979 OS << (Started ? "," : " [");
Benjamin Kramera65cb0c2011-09-26 02:14:13 +0000980 Started = true;
Chandler Carruth53a529e2011-09-26 00:44:09 +0000981 if (DiagOpts.ShowCategories == 1)
Benjamin Kramera65cb0c2011-09-26 02:14:13 +0000982 OS << DiagCategory;
Chandler Carruth53a529e2011-09-26 00:44:09 +0000983 else {
984 assert(DiagOpts.ShowCategories == 2 && "Invalid ShowCategories value");
985 OS << DiagnosticIDs::getCategoryNameFromID(DiagCategory);
986 }
987 }
Chandler Carruth53a529e2011-09-26 00:44:09 +0000988 }
Benjamin Kramera65cb0c2011-09-26 02:14:13 +0000989 if (Started)
990 OS << ']';
Chandler Carruth53a529e2011-09-26 00:44:09 +0000991}
992
Chandler Carruth8dcdde12011-09-26 10:58:00 +0000993/// \brief Skip over whitespace in the string, starting at the given
994/// index.
995///
996/// \returns The index of the first non-whitespace character that is
997/// greater than or equal to Idx or, if no such character exists,
998/// returns the end of the string.
Chandler Carruth75c1bef2011-09-26 11:19:35 +0000999static unsigned skipWhitespace(unsigned Idx, StringRef Str, unsigned Length) {
Chandler Carruth8dcdde12011-09-26 10:58:00 +00001000 while (Idx < Length && isspace(Str[Idx]))
1001 ++Idx;
1002 return Idx;
1003}
1004
1005/// \brief If the given character is the start of some kind of
1006/// balanced punctuation (e.g., quotes or parentheses), return the
1007/// character that will terminate the punctuation.
1008///
1009/// \returns The ending punctuation character, if any, or the NULL
1010/// character if the input character does not start any punctuation.
1011static inline char findMatchingPunctuation(char c) {
1012 switch (c) {
1013 case '\'': return '\'';
1014 case '`': return '\'';
1015 case '"': return '"';
1016 case '(': return ')';
1017 case '[': return ']';
1018 case '{': return '}';
1019 default: break;
1020 }
1021
1022 return 0;
1023}
1024
1025/// \brief Find the end of the word starting at the given offset
1026/// within a string.
1027///
1028/// \returns the index pointing one character past the end of the
1029/// word.
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001030static unsigned findEndOfWord(unsigned Start, StringRef Str,
Chandler Carruth8dcdde12011-09-26 10:58:00 +00001031 unsigned Length, unsigned Column,
1032 unsigned Columns) {
1033 assert(Start < Str.size() && "Invalid start position!");
1034 unsigned End = Start + 1;
1035
1036 // If we are already at the end of the string, take that as the word.
1037 if (End == Str.size())
1038 return End;
1039
1040 // Determine if the start of the string is actually opening
1041 // punctuation, e.g., a quote or parentheses.
1042 char EndPunct = findMatchingPunctuation(Str[Start]);
1043 if (!EndPunct) {
1044 // This is a normal word. Just find the first space character.
1045 while (End < Length && !isspace(Str[End]))
1046 ++End;
1047 return End;
1048 }
1049
1050 // We have the start of a balanced punctuation sequence (quotes,
1051 // parentheses, etc.). Determine the full sequence is.
1052 llvm::SmallString<16> PunctuationEndStack;
1053 PunctuationEndStack.push_back(EndPunct);
1054 while (End < Length && !PunctuationEndStack.empty()) {
1055 if (Str[End] == PunctuationEndStack.back())
1056 PunctuationEndStack.pop_back();
1057 else if (char SubEndPunct = findMatchingPunctuation(Str[End]))
1058 PunctuationEndStack.push_back(SubEndPunct);
1059
1060 ++End;
1061 }
1062
1063 // Find the first space character after the punctuation ended.
1064 while (End < Length && !isspace(Str[End]))
1065 ++End;
1066
1067 unsigned PunctWordLength = End - Start;
1068 if (// If the word fits on this line
1069 Column + PunctWordLength <= Columns ||
1070 // ... or the word is "short enough" to take up the next line
1071 // without too much ugly white space
1072 PunctWordLength < Columns/3)
1073 return End; // Take the whole thing as a single "word".
1074
1075 // The whole quoted/parenthesized string is too long to print as a
1076 // single "word". Instead, find the "word" that starts just after
1077 // the punctuation and use that end-point instead. This will recurse
1078 // until it finds something small enough to consider a word.
1079 return findEndOfWord(Start + 1, Str, Length, Column + 1, Columns);
1080}
1081
Chandler Carruth45b19de2011-09-26 01:44:27 +00001082/// \brief Print the given string to a stream, word-wrapping it to
1083/// some number of columns in the process.
1084///
1085/// \param OS the stream to which the word-wrapping string will be
1086/// emitted.
1087/// \param Str the string to word-wrap and output.
1088/// \param Columns the number of columns to word-wrap to.
1089/// \param Column the column number at which the first character of \p
1090/// Str will be printed. This will be non-zero when part of the first
1091/// line has already been printed.
1092/// \param Indentation the number of spaces to indent any lines beyond
1093/// the first line.
1094/// \returns true if word-wrapping was required, or false if the
1095/// string fit on the first line.
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001096static bool printWordWrapped(raw_ostream &OS, StringRef Str,
Chandler Carruth45b19de2011-09-26 01:44:27 +00001097 unsigned Columns,
1098 unsigned Column = 0,
1099 unsigned Indentation = WordWrapIndentation) {
Chandler Carruth3a218092011-09-26 01:44:29 +00001100 const unsigned Length = Str.size();
Chandler Carruth45b19de2011-09-26 01:44:27 +00001101
1102 // The string used to indent each line.
1103 llvm::SmallString<16> IndentStr;
1104 IndentStr.assign(Indentation, ' ');
1105 bool Wrapped = false;
1106 for (unsigned WordStart = 0, WordEnd; WordStart < Length;
1107 WordStart = WordEnd) {
1108 // Find the beginning of the next word.
1109 WordStart = skipWhitespace(WordStart, Str, Length);
1110 if (WordStart == Length)
1111 break;
1112
1113 // Find the end of this word.
1114 WordEnd = findEndOfWord(WordStart, Str, Length, Column, Columns);
1115
1116 // Does this word fit on the current line?
1117 unsigned WordLength = WordEnd - WordStart;
1118 if (Column + WordLength < Columns) {
1119 // This word fits on the current line; print it there.
1120 if (WordStart) {
1121 OS << ' ';
1122 Column += 1;
1123 }
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001124 OS << Str.substr(WordStart, WordLength);
Chandler Carruth45b19de2011-09-26 01:44:27 +00001125 Column += WordLength;
1126 continue;
1127 }
1128
1129 // This word does not fit on the current line, so wrap to the next
1130 // line.
1131 OS << '\n';
1132 OS.write(&IndentStr[0], Indentation);
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001133 OS << Str.substr(WordStart, WordLength);
Chandler Carruth45b19de2011-09-26 01:44:27 +00001134 Column = Indentation + WordLength;
1135 Wrapped = true;
1136 }
1137
Chandler Carruth3a218092011-09-26 01:44:29 +00001138 return Wrapped;
Chandler Carruth45b19de2011-09-26 01:44:27 +00001139}
1140
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001141static void printDiagnosticMessage(raw_ostream &OS,
1142 DiagnosticsEngine::Level Level,
1143 StringRef Message,
1144 unsigned CurrentColumn, unsigned Columns,
1145 bool ShowColors) {
1146 if (ShowColors) {
1147 // Print warnings, errors and fatal errors in bold, no color
1148 switch (Level) {
1149 case DiagnosticsEngine::Warning: OS.changeColor(savedColor, true); break;
1150 case DiagnosticsEngine::Error: OS.changeColor(savedColor, true); break;
1151 case DiagnosticsEngine::Fatal: OS.changeColor(savedColor, true); break;
1152 default: break; //don't bold notes
1153 }
1154 }
1155
1156 if (Columns)
1157 printWordWrapped(OS, Message, Columns, CurrentColumn);
1158 else
1159 OS << Message;
1160
1161 if (ShowColors)
1162 OS.resetColor();
1163 OS << '\n';
1164}
1165
Chandler Carrutha6290042011-09-26 00:26:47 +00001166void TextDiagnosticPrinter::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +00001167 const Diagnostic &Info) {
Chandler Carrutha6290042011-09-26 00:26:47 +00001168 // Default implementation (Warnings/errors count).
1169 DiagnosticConsumer::HandleDiagnostic(Level, Info);
1170
Chandler Carruth0ef89882011-09-26 11:25:30 +00001171 // Render the diagnostic message into a temporary buffer eagerly. We'll use
1172 // this later as we print out the diagnostic to the terminal.
1173 llvm::SmallString<100> OutStr;
1174 Info.FormatDiagnostic(OutStr);
1175
1176 llvm::raw_svector_ostream DiagMessageStream(OutStr);
1177 if (DiagOpts->ShowNames)
1178 printDiagnosticName(DiagMessageStream, Info);
1179 printDiagnosticOptions(DiagMessageStream, Level, Info, *DiagOpts);
1180
1181
Chandler Carrutha6290042011-09-26 00:26:47 +00001182 // Keeps track of the the starting position of the location
1183 // information (e.g., "foo.c:10:4:") that precedes the error
1184 // message. We use this information to determine how long the
1185 // file+line+column number prefix is.
1186 uint64_t StartOfLocationInfo = OS.tell();
1187
1188 if (!Prefix.empty())
1189 OS << Prefix << ": ";
1190
Chandler Carruth0ef89882011-09-26 11:25:30 +00001191 // Use a dedicated, simpler path for diagnostics without a valid location.
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001192 // This is important as if the location is missing, we may be emitting
1193 // diagnostics in a context that lacks language options, a source manager, or
1194 // other infrastructure necessary when emitting more rich diagnostics.
Chandler Carruth0ef89882011-09-26 11:25:30 +00001195 if (!Info.getLocation().isValid()) {
1196 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
1197 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1198 OS.tell() - StartOfLocationInfo,
1199 DiagOpts->MessageLength, DiagOpts->ShowColors);
1200 OS.flush();
1201 return;
Chandler Carrutha6290042011-09-26 00:26:47 +00001202 }
1203
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001204 // Assert that the rest of our infrastructure is setup properly.
1205 assert(LangOpts && "Unexpected diagnostic outside source file processing");
1206 assert(DiagOpts && "Unexpected diagnostic without options set");
1207 assert(Info.hasSourceManager() &&
1208 "Unexpected diagnostic with no source manager");
Chandler Carruth0ef89882011-09-26 11:25:30 +00001209 const SourceManager &SM = Info.getSourceManager();
Chandler Carruthe6d1dff2011-09-26 11:38:46 +00001210 TextDiagnostic TextDiag(*this, OS, SM, *LangOpts, *DiagOpts);
1211
Chandler Carruth0ef89882011-09-26 11:25:30 +00001212 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Info.getLocation());
1213
1214 // First, if this diagnostic is not in the main file, print out the
1215 // "included from" lines.
1216 PrintIncludeStack(Level, PLoc.getIncludeLoc(), SM);
1217 StartOfLocationInfo = OS.tell();
1218
1219 // Next emit the location of this particular diagnostic.
1220 EmitDiagnosticLoc(Level, Info, SM, PLoc);
1221
1222 if (DiagOpts->ShowColors)
1223 OS.resetColor();
1224
Chandler Carrutha3ba6bb2011-09-26 01:30:09 +00001225 printDiagnosticLevel(OS, Level, DiagOpts->ShowColors);
Chandler Carruth75c1bef2011-09-26 11:19:35 +00001226 printDiagnosticMessage(OS, Level, DiagMessageStream.str(),
1227 OS.tell() - StartOfLocationInfo,
1228 DiagOpts->MessageLength, DiagOpts->ShowColors);
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001229
Douglas Gregordf667e72009-03-10 20:44:00 +00001230 // If caret diagnostics are enabled and we have location, we want to
1231 // emit the caret. However, we only do this if the location moved
1232 // from the last diagnostic, if the last diagnostic was a note that
1233 // was part of a different warning or error diagnostic, or if the
1234 // diagnostic has ranges. We don't want to emit the same caret
1235 // multiple times if one loc has multiple diagnostics.
Chandler Carruth0ef89882011-09-26 11:25:30 +00001236 if (DiagOpts->ShowCarets &&
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001237 ((LastLoc != Info.getLocation()) || Info.getNumRanges() ||
David Blaikied6471f72011-09-25 23:23:43 +00001238 (LastCaretDiagnosticWasNote && Level != DiagnosticsEngine::Note) ||
Douglas Gregor849b2432010-03-31 17:46:05 +00001239 Info.getNumFixItHints())) {
Steve Naroffefe7f362008-02-08 22:06:17 +00001240 // Cache the LastLoc, it allows us to omit duplicate source/caret spewage.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00001241 LastLoc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
David Blaikied6471f72011-09-25 23:23:43 +00001242 LastCaretDiagnosticWasNote = (Level == DiagnosticsEngine::Note);
Chris Lattnerb9c3f962009-01-27 07:57:44 +00001243
Chris Lattnerebbbb1b2009-02-20 00:18:51 +00001244 // Get the ranges into a local array we can hack on.
Chandler Carruth5182a182011-09-07 01:47:09 +00001245 SmallVector<CharSourceRange, 20> Ranges;
1246 Ranges.reserve(Info.getNumRanges());
1247 for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
1248 Ranges.push_back(Info.getRange(i));
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001249
Chandler Carruth5182a182011-09-07 01:47:09 +00001250 for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i) {
Chris Lattner0a76aae2010-06-18 22:45:06 +00001251 const FixItHint &Hint = Info.getFixItHint(i);
Chandler Carruth5182a182011-09-07 01:47:09 +00001252 if (Hint.RemoveRange.isValid())
1253 Ranges.push_back(Hint.RemoveRange);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +00001254 }
1255
Chandler Carruth026cb762011-09-25 23:01:05 +00001256 unsigned MacroDepth = 0;
1257 TextDiag.Emit(LastLoc, Ranges, llvm::makeArrayRef(Info.getFixItHints(),
1258 Info.getNumFixItHints()),
1259 MacroDepth);
Reid Spencer5f016e22007-07-11 17:01:13 +00001260 }
Daniel Dunbarcbff0dc2009-09-07 23:07:56 +00001261
Chris Lattnera03a5b52008-11-19 06:56:25 +00001262 OS.flush();
Reid Spencer5f016e22007-07-11 17:01:13 +00001263}