1 //===--- 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"
15 #include "clang/Edit/EditedSource.h"
16 #include "clang/Edit/Commit.h"
17 #include "clang/Edit/EditsReceiver.h"
18 #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>
23 using 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.
skipToMacroArgExpansion(const SourceManager & SM,SourceLocation StartLoc)29 static 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.
getImmediateMacroCallerLoc(const SourceManager & SM,SourceLocation Loc)43 static 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.
getImmediateMacroCalleeLoc(const SourceManager & SM,SourceLocation Loc)60 static 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
75 /// \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".
getImmediateMacroName(SourceLocation Loc,const SourceManager & SM,const LangOptions & LangOpts)91 static 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
112 /// Get the presumed location of a diagnostic message. This computes the
113 /// presumed location for the top of any macro backtrace when present.
getDiagnosticPresumedLoc(const SourceManager & SM,SourceLocation Loc)114 static 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
DiagnosticRenderer(const SourceManager & SM,const LangOptions & LangOpts,const DiagnosticOptions & DiagOpts)126 DiagnosticRenderer::DiagnosticRenderer(const SourceManager &SM,
127 const LangOptions &LangOpts,
128 const DiagnosticOptions &DiagOpts)
129 : SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
130
~DiagnosticRenderer()131 DiagnosticRenderer::~DiagnosticRenderer() {}
132
133 namespace {
134
135 class FixitReceiver : public edit::EditsReceiver {
136 SmallVectorImpl<FixItHint> &MergedFixits;
137
138 public:
FixitReceiver(SmallVectorImpl<FixItHint> & MergedFixits)139 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
140 : MergedFixits(MergedFixits) { }
insert(SourceLocation loc,StringRef text)141 virtual void insert(SourceLocation loc, StringRef text) {
142 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
143 }
replace(CharSourceRange range,StringRef text)144 virtual void replace(CharSourceRange range, StringRef text) {
145 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
146 }
147 };
148
149 }
150
mergeFixits(ArrayRef<FixItHint> FixItHints,const SourceManager & SM,const LangOptions & LangOpts,SmallVectorImpl<FixItHint> & MergedFixits)151 static void mergeFixits(ArrayRef<FixItHint> FixItHints,
152 const SourceManager &SM, const LangOptions &LangOpts,
153 SmallVectorImpl<FixItHint> &MergedFixits) {
154 edit::Commit commit(SM, LangOpts);
155 for (ArrayRef<FixItHint>::const_iterator
156 I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
157 const FixItHint &Hint = *I;
158 if (Hint.CodeToInsert.empty()) {
159 if (Hint.InsertFromRange.isValid())
160 commit.insertFromRange(Hint.RemoveRange.getBegin(),
161 Hint.InsertFromRange, /*afterToken=*/false,
162 Hint.BeforePreviousInsertions);
163 else
164 commit.remove(Hint.RemoveRange);
165 } else {
166 if (Hint.RemoveRange.isTokenRange() ||
167 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
168 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
169 else
170 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
171 /*afterToken=*/false, Hint.BeforePreviousInsertions);
172 }
173 }
174
175 edit::EditedSource Editor(SM, LangOpts);
176 if (Editor.commit(commit)) {
177 FixitReceiver Rec(MergedFixits);
178 Editor.applyRewrites(Rec);
179 }
180 }
181
emitDiagnostic(SourceLocation Loc,DiagnosticsEngine::Level Level,StringRef Message,ArrayRef<CharSourceRange> Ranges,ArrayRef<FixItHint> FixItHints,DiagOrStoredDiag D)182 void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
183 DiagnosticsEngine::Level Level,
184 StringRef Message,
185 ArrayRef<CharSourceRange> Ranges,
186 ArrayRef<FixItHint> FixItHints,
187 DiagOrStoredDiag D) {
188
189 beginDiagnostic(D, Level);
190
191 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
192
193 // First, if this diagnostic is not in the main file, print out the
194 // "included from" lines.
195 emitIncludeStack(PLoc.getIncludeLoc(), Level);
196
197 // Next, emit the actual diagnostic message.
198 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
199
200 // Only recurse if we have a valid location.
201 if (Loc.isValid()) {
202 // Get the ranges into a local array we can hack on.
203 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
204 Ranges.end());
205
206 llvm::SmallVector<FixItHint, 8> MergedFixits;
207 if (!FixItHints.empty()) {
208 mergeFixits(FixItHints, SM, LangOpts, MergedFixits);
209 FixItHints = MergedFixits;
210 }
211
212 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
213 E = FixItHints.end();
214 I != E; ++I)
215 if (I->RemoveRange.isValid())
216 MutableRanges.push_back(I->RemoveRange);
217
218 unsigned MacroDepth = 0;
219 emitMacroExpansionsAndCarets(Loc, Level, MutableRanges, FixItHints,
220 MacroDepth);
221 }
222
223 LastLoc = Loc;
224 LastLevel = Level;
225
226 endDiagnostic(D, Level);
227 }
228
229
emitStoredDiagnostic(StoredDiagnostic & Diag)230 void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
231 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
232 Diag.getRanges(), Diag.getFixIts(),
233 &Diag);
234 }
235
236 /// \brief Prints an include stack when appropriate for a particular
237 /// diagnostic level and location.
238 ///
239 /// This routine handles all the logic of suppressing particular include
240 /// stacks (such as those for notes) and duplicate include stacks when
241 /// repeated warnings occur within the same file. It also handles the logic
242 /// of customizing the formatting and display of the include stack.
243 ///
244 /// \param Level The diagnostic level of the message this stack pertains to.
245 /// \param Loc The include location of the current file (not the diagnostic
246 /// location).
emitIncludeStack(SourceLocation Loc,DiagnosticsEngine::Level Level)247 void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
248 DiagnosticsEngine::Level Level) {
249 // Skip redundant include stacks altogether.
250 if (LastIncludeLoc == Loc)
251 return;
252 LastIncludeLoc = Loc;
253
254 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
255 return;
256
257 emitIncludeStackRecursively(Loc);
258 }
259
260 /// \brief Helper to recursivly walk up the include stack and print each layer
261 /// on the way back down.
emitIncludeStackRecursively(SourceLocation Loc)262 void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc) {
263 if (Loc.isInvalid())
264 return;
265
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
267 if (PLoc.isInvalid())
268 return;
269
270 // Emit the other include frames first.
271 emitIncludeStackRecursively(PLoc.getIncludeLoc());
272
273 // Emit the inclusion text/note.
274 emitIncludeLocation(Loc, PLoc);
275 }
276
277 /// \brief Recursively emit notes for each macro expansion and caret
278 /// diagnostics where appropriate.
279 ///
280 /// Walks up the macro expansion stack printing expansion notes, the code
281 /// snippet, caret, underlines and FixItHint display as appropriate at each
282 /// level.
283 ///
284 /// \param Loc The location for this caret.
285 /// \param Level The diagnostic level currently being emitted.
286 /// \param Ranges The underlined ranges for this code snippet.
287 /// \param Hints The FixIt hints active for this diagnostic.
288 /// \param MacroSkipEnd The depth to stop skipping macro expansions.
289 /// \param OnMacroInst The current depth of the macro expansion stack.
emitMacroExpansionsAndCarets(SourceLocation Loc,DiagnosticsEngine::Level Level,SmallVectorImpl<CharSourceRange> & Ranges,ArrayRef<FixItHint> Hints,unsigned & MacroDepth,unsigned OnMacroInst)290 void DiagnosticRenderer::emitMacroExpansionsAndCarets(
291 SourceLocation Loc,
292 DiagnosticsEngine::Level Level,
293 SmallVectorImpl<CharSourceRange>& Ranges,
294 ArrayRef<FixItHint> Hints,
295 unsigned &MacroDepth,
296 unsigned OnMacroInst)
297 {
298 assert(!Loc.isInvalid() && "must have a valid source location here");
299
300 // If this is a file source location, directly emit the source snippet and
301 // caret line. Also record the macro depth reached.
302 if (Loc.isFileID()) {
303 assert(MacroDepth == 0 && "We shouldn't hit a leaf node twice!");
304 MacroDepth = OnMacroInst;
305 emitCodeContext(Loc, Level, Ranges, Hints);
306 return;
307 }
308 // Otherwise recurse through each macro expansion layer.
309
310 // When processing macros, skip over the expansions leading up to
311 // a macro argument, and trace the argument's expansion stack instead.
312 Loc = skipToMacroArgExpansion(SM, Loc);
313
314 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
315
316 // FIXME: Map ranges?
317 emitMacroExpansionsAndCarets(OneLevelUp, Level, Ranges, Hints, MacroDepth,
318 OnMacroInst + 1);
319
320 // Save the original location so we can find the spelling of the macro call.
321 SourceLocation MacroLoc = Loc;
322
323 // Map the location.
324 Loc = getImmediateMacroCalleeLoc(SM, Loc);
325
326 unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
327 if (MacroDepth > DiagOpts.MacroBacktraceLimit &&
328 DiagOpts.MacroBacktraceLimit != 0) {
329 MacroSkipStart = DiagOpts.MacroBacktraceLimit / 2 +
330 DiagOpts.MacroBacktraceLimit % 2;
331 MacroSkipEnd = MacroDepth - DiagOpts.MacroBacktraceLimit / 2;
332 }
333
334 // Whether to suppress printing this macro expansion.
335 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
336 OnMacroInst < MacroSkipEnd);
337
338 // Map the ranges.
339 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
340 E = Ranges.end();
341 I != E; ++I) {
342 SourceLocation Start = I->getBegin(), End = I->getEnd();
343 if (Start.isMacroID())
344 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
345 if (End.isMacroID())
346 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
347 }
348
349 if (Suppressed) {
350 // Tell the user that we've skipped contexts.
351 if (OnMacroInst == MacroSkipStart) {
352 SmallString<200> MessageStorage;
353 llvm::raw_svector_ostream Message(MessageStorage);
354 Message << "(skipping " << (MacroSkipEnd - MacroSkipStart)
355 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
356 "see all)";
357 emitBasicNote(Message.str());
358 }
359 return;
360 }
361
362 SmallString<100> MessageStorage;
363 llvm::raw_svector_ostream Message(MessageStorage);
364 Message << "expanded from macro '"
365 << getImmediateMacroName(MacroLoc, SM, LangOpts) << "'";
366 emitDiagnostic(SM.getSpellingLoc(Loc), DiagnosticsEngine::Note,
367 Message.str(),
368 Ranges, ArrayRef<FixItHint>());
369 }
370
~DiagnosticNoteRenderer()371 DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
372
emitIncludeLocation(SourceLocation Loc,PresumedLoc PLoc)373 void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
374 PresumedLoc PLoc) {
375 // Generate a note indicating the include location.
376 SmallString<200> MessageStorage;
377 llvm::raw_svector_ostream Message(MessageStorage);
378 Message << "in file included from " << PLoc.getFilename() << ':'
379 << PLoc.getLine() << ":";
380 emitNote(Loc, Message.str());
381 }
382
emitBasicNote(StringRef Message)383 void DiagnosticNoteRenderer::emitBasicNote(StringRef Message) {
384 emitNote(SourceLocation(), Message);
385 }
386
387