1 //===--- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
23 using namespace clang;
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.
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))
37 // Otherwise just return initial location, there's nothing to skip.
41 /// Gets the location of the immediate macro caller, one level up the stack
42 /// toward the initial macro typed into the source.
43 static SourceLocation getImmediateMacroCallerLoc(const SourceManager &SM,
45 if (!Loc.isMacroID()) return Loc;
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);
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;
58 /// Gets the location of the immediate macro callee, one level down the stack
59 /// toward the leaf macro.
60 static SourceLocation getImmediateMacroCalleeLoc(const SourceManager &SM,
62 if (!Loc.isMacroID()) return Loc;
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;
70 // Otherwise, the callee of the macro is located where this location was
71 // spelled inside the macro definition.
72 return SM.getImmediateSpellingLoc(Loc);
75 /// \brief Retrieve the name of the immediate macro expansion.
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.
83 /// This differs from Lexer::getImmediateMacroName in that any macro argument
84 /// location will result in the topmost function macro that accepted it.
89 /// for location of 'foo' token, this function will return "MAC1" while
90 /// Lexer::getImmediateMacroName will return "MAC2".
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;
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);
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);
112 /// Get the presumed location of a diagnostic message. This computes the
113 /// presumed location for the top of any macro backtrace when present.
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);
123 return SM.getPresumedLoc(Loc);
126 DiagnosticRenderer::DiagnosticRenderer(const SourceManager &SM,
127 const LangOptions &LangOpts,
128 const DiagnosticOptions &DiagOpts)
129 : SM(SM), LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
131 DiagnosticRenderer::~DiagnosticRenderer() {}
135 class FixitReceiver : public edit::EditsReceiver {
136 SmallVectorImpl<FixItHint> &MergedFixits;
139 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
140 : MergedFixits(MergedFixits) { }
141 virtual void insert(SourceLocation loc, StringRef text) {
142 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
144 virtual void replace(CharSourceRange range, StringRef text) {
145 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
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);
164 commit.remove(Hint.RemoveRange);
166 if (Hint.RemoveRange.isTokenRange() ||
167 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
168 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
170 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
171 /*afterToken=*/false, Hint.BeforePreviousInsertions);
175 edit::EditedSource Editor(SM, LangOpts);
176 if (Editor.commit(commit)) {
177 FixitReceiver Rec(MergedFixits);
178 Editor.applyRewrites(Rec);
182 void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
183 DiagnosticsEngine::Level Level,
185 ArrayRef<CharSourceRange> Ranges,
186 ArrayRef<FixItHint> FixItHints,
187 DiagOrStoredDiag D) {
189 beginDiagnostic(D, Level);
191 PresumedLoc PLoc = getDiagnosticPresumedLoc(SM, Loc);
193 // First, if this diagnostic is not in the main file, print out the
194 // "included from" lines.
195 emitIncludeStack(PLoc.getIncludeLoc(), Level);
197 // Next, emit the actual diagnostic message.
198 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
200 // Only recurse if we have a valid location.
202 // Get the ranges into a local array we can hack on.
203 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
206 llvm::SmallVector<FixItHint, 8> MergedFixits;
207 if (!FixItHints.empty()) {
208 mergeFixits(FixItHints, SM, LangOpts, MergedFixits);
209 FixItHints = MergedFixits;
212 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
213 E = FixItHints.end();
215 if (I->RemoveRange.isValid())
216 MutableRanges.push_back(I->RemoveRange);
218 unsigned MacroDepth = 0;
219 emitMacroExpansionsAndCarets(Loc, Level, MutableRanges, FixItHints,
226 endDiagnostic(D, Level);
230 void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
231 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
232 Diag.getRanges(), Diag.getFixIts(),
236 /// \brief Prints an include stack when appropriate for a particular
237 /// diagnostic level and location.
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.
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
247 void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
248 DiagnosticsEngine::Level Level) {
249 // Skip redundant include stacks altogether.
250 if (LastIncludeLoc == Loc)
252 LastIncludeLoc = Loc;
254 if (!DiagOpts.ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
257 emitIncludeStackRecursively(Loc);
260 /// \brief Helper to recursivly walk up the include stack and print each layer
261 /// on the way back down.
262 void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc) {
266 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
267 if (PLoc.isInvalid())
270 // Emit the other include frames first.
271 emitIncludeStackRecursively(PLoc.getIncludeLoc());
273 // Emit the inclusion text/note.
274 emitIncludeLocation(Loc, PLoc);
277 /// \brief Recursively emit notes for each macro expansion and caret
278 /// diagnostics where appropriate.
280 /// Walks up the macro expansion stack printing expansion notes, the code
281 /// snippet, caret, underlines and FixItHint display as appropriate at each
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.
290 void DiagnosticRenderer::emitMacroExpansionsAndCarets(
292 DiagnosticsEngine::Level Level,
293 SmallVectorImpl<CharSourceRange>& Ranges,
294 ArrayRef<FixItHint> Hints,
295 unsigned &MacroDepth,
296 unsigned OnMacroInst)
298 assert(!Loc.isInvalid() && "must have a valid source location here");
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);
308 // Otherwise recurse through each macro expansion layer.
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);
314 SourceLocation OneLevelUp = getImmediateMacroCallerLoc(SM, Loc);
316 // FIXME: Map ranges?
317 emitMacroExpansionsAndCarets(OneLevelUp, Level, Ranges, Hints, MacroDepth,
320 // Save the original location so we can find the spelling of the macro call.
321 SourceLocation MacroLoc = Loc;
324 Loc = getImmediateMacroCalleeLoc(SM, Loc);
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;
334 // Whether to suppress printing this macro expansion.
335 bool Suppressed = (OnMacroInst >= MacroSkipStart &&
336 OnMacroInst < MacroSkipEnd);
339 for (SmallVectorImpl<CharSourceRange>::iterator I = Ranges.begin(),
342 SourceLocation Start = I->getBegin(), End = I->getEnd();
343 if (Start.isMacroID())
344 I->setBegin(getImmediateMacroCalleeLoc(SM, Start));
346 I->setEnd(getImmediateMacroCalleeLoc(SM, End));
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 "
357 emitBasicNote(Message.str());
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,
368 Ranges, ArrayRef<FixItHint>());
371 DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
373 void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
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());
383 void DiagnosticNoteRenderer::emitBasicNote(StringRef Message) {
384 emitNote(SourceLocation(), Message);