blob: 7249943d3aa6592cde67b019f34c568c46f70773 [file] [log] [blame]
Ted Kremenek2898d4f2011-12-17 05:26:04 +00001//===--- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/DiagnosticRenderer.h"
11#include "clang/Basic/FileManager.h"
12#include "clang/Basic/SourceManager.h"
13#include "clang/Frontend/DiagnosticOptions.h"
14#include "clang/Lex/Lexer.h"
Ted Kremenek30660a82012-03-06 20:06:33 +000015#include "clang/Edit/EditedSource.h"
16#include "clang/Edit/Commit.h"
17#include "clang/Edit/EditsReceiver.h"
Ted Kremenek2898d4f2011-12-17 05:26:04 +000018#include "llvm/Support/MemoryBuffer.h"
19#include "llvm/Support/raw_ostream.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/ADT/SmallString.h"
22#include <algorithm>
23using namespace clang;
24
25/// Look through spelling locations for a macro argument expansion, and
26/// if found skip to it so that we can trace the argument rather than the macros
27/// in which that argument is used. If no macro argument expansion is found,
28/// don't skip anything and return the starting location.
29static SourceLocation skipToMacroArgExpansion(const SourceManager &SM,
30 SourceLocation StartLoc) {
31 for (SourceLocation L = StartLoc; L.isMacroID();
32 L = SM.getImmediateSpellingLoc(L)) {
33 if (SM.isMacroArgExpansion(L))
34 return L;
35 }
36
37 // Otherwise just return initial location, there's nothing to skip.
38 return StartLoc;
39}
40
41/// Gets the location of the immediate macro caller, one level up the stack
42/// toward the initial macro typed into the source.
43static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
44 SourceLocation Loc) {
45 if (!Loc.isMacroID()) return Loc;
46
47 // When we have the location of (part of) an expanded parameter, its spelling
48 // location points to the argument as typed into the macro call, and
49 // therefore is used to locate the macro caller.
50 if (SM.isMacroArgExpansion(Loc))
51 return SM.getImmediateSpellingLoc(Loc);
52
53 // Otherwise, the caller of the macro is located where this macro is
54 // expanded (while the spelling is part of the macro definition).
55 return SM.getImmediateExpansionRange(Loc).first;
56}
57
58/// Gets the location of the immediate macro callee, one level down the stack
59/// toward the leaf macro.
60static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
61 SourceLocation Loc) {
62 if (!Loc.isMacroID()) return Loc;
63
64 // When we have the location of (part of) an expanded parameter, its
65 // expansion location points to the unexpanded paramater reference within
66 // the macro definition (or callee).
67 if (SM.isMacroArgExpansion(Loc))
68 return SM.getImmediateExpansionRange(Loc).first;
69
70 // Otherwise, the callee of the macro is located where this location was
71 // spelled inside the macro definition.
72 return SM.getImmediateSpellingLoc(Loc);
73}
74
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +000075/// \brief Retrieve the name of the immediate macro expansion.
76///
77/// This routine starts from a source location, and finds the name of the macro
78/// responsible for its immediate expansion. It looks through any intervening
79/// macro argument expansions to compute this. It returns a StringRef which
80/// refers to the SourceManager-owned buffer of the source where that macro
81/// name is spelled. Thus, the result shouldn't out-live that SourceManager.
82///
83/// This differs from Lexer::getImmediateMacroName in that any macro argument
84/// location will result in the topmost function macro that accepted it.
85/// e.g.
86/// \code
87/// MAC1( MAC2(foo) )
88/// \endcode
89/// for location of 'foo' token, this function will return "MAC1" while
90/// Lexer::getImmediateMacroName will return "MAC2".
91static StringRef getImmediateMacroName(SourceLocation Loc,
92 const SourceManager &SM,
93 const LangOptions &LangOpts) {
94 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
95 // Walk past macro argument expanions.
96 while (SM.isMacroArgExpansion(Loc))
97 Loc = SM.getImmediateExpansionRange(Loc).first;
98
99 // Find the spelling location of the start of the non-argument expansion
100 // range. This is where the macro name was spelled in order to begin
101 // expanding this macro.
102 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
103
104 // Dig out the buffer where the macro name was spelled and the extents of the
105 // name so that we can render it into the expansion note.
106 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
107 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
108 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
109 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
110}
111
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000112/// Get the presumed location of a diagnostic message. This computes the
113/// presumed location for the top of any macro backtrace when present.
114static PresumedLoc getDiagnosticPresumedLoc(const SourceManager &SM,
115 SourceLocation Loc) {
116 // This is a condensed form of the algorithm used by emitCaretDiagnostic to
117 // walk to the top of the macro call stack.
118 while (Loc.isMacroID()) {
119 Loc = skipToMacroArgExpansion(SM, Loc);
120 Loc = getImmediateMacroCallerLoc(SM, Loc);
121 }
122
123 return SM.getPresumedLoc(Loc);
124}
125
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000126DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000127 const DiagnosticOptions &DiagOpts)
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000128: LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000129
130DiagnosticRenderer::~DiagnosticRenderer() {}
131
Ted Kremenek30660a82012-03-06 20:06:33 +0000132namespace {
133
134class FixitReceiver : public edit::EditsReceiver {
135 SmallVectorImpl<FixItHint> &MergedFixits;
136
137public:
138 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
139 : MergedFixits(MergedFixits) { }
140 virtual void insert(SourceLocation loc, StringRef text) {
141 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
142 }
143 virtual void replace(CharSourceRange range, StringRef text) {
144 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
145 }
146};
147
148}
149
150static void mergeFixits(ArrayRef<FixItHint> FixItHints,
151 const SourceManager &SM, const LangOptions &LangOpts,
152 SmallVectorImpl<FixItHint> &MergedFixits) {
153 edit::Commit commit(SM, LangOpts);
154 for (ArrayRef<FixItHint>::const_iterator
155 I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
156 const FixItHint &Hint = *I;
157 if (Hint.CodeToInsert.empty()) {
158 if (Hint.InsertFromRange.isValid())
159 commit.insertFromRange(Hint.RemoveRange.getBegin(),
160 Hint.InsertFromRange, /*afterToken=*/false,
161 Hint.BeforePreviousInsertions);
162 else
163 commit.remove(Hint.RemoveRange);
164 } else {
165 if (Hint.RemoveRange.isTokenRange() ||
166 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
167 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
168 else
169 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
170 /*afterToken=*/false, Hint.BeforePreviousInsertions);
171 }
172 }
173
174 edit::EditedSource Editor(SM, LangOpts);
175 if (Editor.commit(commit)) {
176 FixitReceiver Rec(MergedFixits);
177 Editor.applyRewrites(Rec);
178 }
179}
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000180
181void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
182 DiagnosticsEngine::Level Level,
183 StringRef Message,
184 ArrayRef<CharSourceRange> Ranges,
185 ArrayRef<FixItHint> FixItHints,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000186 const SourceManager *SM,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000187 DiagOrStoredDiag D) {
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000188 assert(SM || Loc.isInvalid());
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000189
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000190 beginDiagnostic(D, Level);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000191
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000192 PresumedLoc PLoc;
193 if (Loc.isValid()) {
194 PLoc = getDiagnosticPresumedLoc(*SM, Loc);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000195
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000196 // First, if this diagnostic is not in the main file, print out the
197 // "included from" lines.
198 emitIncludeStack(PLoc.getIncludeLoc(), Level, *SM);
199 }
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000200
201 // Next, emit the actual diagnostic message.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000202 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000203
204 // Only recurse if we have a valid location.
205 if (Loc.isValid()) {
206 // Get the ranges into a local array we can hack on.
207 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
208 Ranges.end());
209
Ted Kremenek30660a82012-03-06 20:06:33 +0000210 llvm::SmallVector<FixItHint, 8> MergedFixits;
211 if (!FixItHints.empty()) {
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000212 mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
Ted Kremenek30660a82012-03-06 20:06:33 +0000213 FixItHints = MergedFixits;
214 }
215
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000216 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
217 E = FixItHints.end();
218 I != E; ++I)
219 if (I->RemoveRange.isValid())
220 MutableRanges.push_back(I->RemoveRange);
221
222 unsigned MacroDepth = 0;
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000223 emitMacroExpansionsAndCarets(Loc, Level, MutableRanges, FixItHints, *SM,
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000224 MacroDepth);
225 }
226
227 LastLoc = Loc;
228 LastLevel = Level;
229
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000230 endDiagnostic(D, Level);
231}
232
233
234void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
235 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
236 Diag.getRanges(), Diag.getFixIts(),
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000237 Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
238 : 0,
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000239 &Diag);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000240}
241
242/// \brief Prints an include stack when appropriate for a particular
243/// diagnostic level and location.
244///
245/// This routine handles all the logic of suppressing particular include
246/// stacks (such as those for notes) and duplicate include stacks when
247/// repeated warnings occur within the same file. It also handles the logic
248/// of customizing the formatting and display of the include stack.
249///
250/// \param Level The diagnostic level of the message this stack pertains to.
251/// \param Loc The include location of the current file (not the diagnostic
252/// location).
253void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000254 DiagnosticsEngine::Level Level,
255 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000256 // Skip redundant include stacks altogether.
257 if (LastIncludeLoc == Loc)
258 return;
259 LastIncludeLoc = Loc;
260
261 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
262 return;
263
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000264 emitIncludeStackRecursively(Loc, SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000265}
266
267/// \brief Helper to recursivly walk up the include stack and print each layer
268/// on the way back down.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000269void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
270 const SourceManager &SM) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000271 if (Loc.isInvalid())
272 return;
273
274 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
275 if (PLoc.isInvalid())
276 return;
277
278 // Emit the other include frames first.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000279 emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000280
281 // Emit the inclusion text/note.
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000282 emitIncludeLocation(Loc, PLoc, SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000283}
284
285/// \brief Recursively emit notes for each macro expansion and caret
286/// diagnostics where appropriate.
287///
288/// Walks up the macro expansion stack printing expansion notes, the code
289/// snippet, caret, underlines and FixItHint display as appropriate at each
290/// level.
291///
292/// \param Loc The location for this caret.
293/// \param Level The diagnostic level currently being emitted.
294/// \param Ranges The underlined ranges for this code snippet.
295/// \param Hints The FixIt hints active for this diagnostic.
296/// \param MacroSkipEnd The depth to stop skipping macro expansions.
297/// \param OnMacroInst The current depth of the macro expansion stack.
298void DiagnosticRenderer::emitMacroExpansionsAndCarets(
299 SourceLocation Loc,
300 DiagnosticsEngine::Level Level,
301 SmallVectorImpl<CharSourceRange>& Ranges,
302 ArrayRef<FixItHint> Hints,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000303 const SourceManager &SM,
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000304 unsigned &MacroDepth,
305 unsigned OnMacroInst)
306{
307 assert(!Loc.isInvalid() && "must have a valid source location here");
308
309 // If this is a file source location, directly emit the source snippet and
310 // caret line. Also record the macro depth reached.
311 if (Loc.isFileID()) {
312 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
313 MacroDepth = OnMacroInst;
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000314 emitCodeContext(Loc, Level, Ranges, Hints, SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000315 return;
316 }
317 // Otherwise recurse through each macro expansion layer.
318
319 // When processing macros, skip over the expansions leading up to
320 // a macro argument, and trace the argument's expansion stack instead.
321 Loc = skipToMacroArgExpansion(SM, Loc);
322
323 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
324
325 // FIXME: Map ranges?
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000326 emitMacroExpansionsAndCarets(OneLevelUp, Level, Ranges, Hints, SM, MacroDepth,
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000327 OnMacroInst + 1);
328
329 // Save the original location so we can find the spelling of the macro call.
330 SourceLocation MacroLoc = Loc;
331
332 // Map the location.
333 Loc = getImmediateMacroCalleeLoc(SM, Loc);
334
335 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
Ted Kremenekcf2362b2012-01-25 06:07:15 +0000336 if (MacroDepth > DiagOpts.MacroBacktraceLimit &&
337 DiagOpts.MacroBacktraceLimit != 0) {
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000338 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
339 DiagOpts.MacroBacktraceLimit % 2;
340 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
341 }
342
343 // Whether to suppress printing this macro expansion.
344 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
345 OnMacroInst < MacroSkipEnd);
346
347 // Map the ranges.
348 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
349 E = Ranges.end();
350 I != E; ++I) {
351 SourceLocation Start = I->getBegin(), End = I->getEnd();
352 if (Start.isMacroID())
353 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
354 if (End.isMacroID())
355 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
356 }
357
358 if (Suppressed) {
359 // Tell the user that we've skipped contexts.
360 if (OnMacroInst == MacroSkipStart) {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000361 SmallString<200> MessageStorage;
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000362 llvm::raw_svector_ostream Message(MessageStorage);
363 Message << "(skipping " << (MacroSkipEnd - MacroSkipStart)
364 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
365 "see all)";
366 emitBasicNote(Message.str());
367 }
368 return;
369 }
370
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000371 SmallString<100> MessageStorage;
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000372 llvm::raw_svector_ostream Message(MessageStorage);
373 Message << "expanded from macro '"
Argyrios Kyrtzidis7f6cf972012-01-23 16:58:33 +0000374 << getImmediateMacroName(MacroLoc, SM, LangOpts) << "'";
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000375 emitDiagnostic(SM.getSpellingLoc(Loc), DiagnosticsEngine::Note,
376 Message.str(),
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000377 Ranges, ArrayRef<FixItHint>(), &SM);
Ted Kremenek2898d4f2011-12-17 05:26:04 +0000378}
379
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000380DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
381
382void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000383 PresumedLoc PLoc,
384 const SourceManager &SM) {
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000385 // Generate a note indicating the include location.
386 SmallString<200> MessageStorage;
387 llvm::raw_svector_ostream Message(MessageStorage);
388 Message << "in file included from " << PLoc.getFilename() << ':'
389 << PLoc.getLine() << ":";
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000390 emitNote(Loc, Message.str(), &SM);
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000391}
392
393void DiagnosticNoteRenderer::emitBasicNote(StringRef Message) {
Argyrios Kyrtzidis16afdf72012-05-10 05:03:45 +0000394 emitNote(SourceLocation(), Message, 0);
Ted Kremenek8be51ea2012-02-14 02:46:00 +0000395}
396