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/DiagnosticOptions.h"
12#include "clang/Basic/FileManager.h"
13#include "clang/Basic/SourceManager.h"
14#include "clang/Edit/Commit.h"
15#include "clang/Edit/EditedSource.h"
16#include "clang/Edit/EditsReceiver.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/raw_ostream.h"
23#include <algorithm>
24using namespace clang;
25
26/// \brief Retrieve the name of the immediate macro expansion.
27///
28/// This routine starts from a source location, and finds the name of the macro
29/// responsible for its immediate expansion. It looks through any intervening
30/// macro argument expansions to compute this. It returns a StringRef which
31/// refers to the SourceManager-owned buffer of the source where that macro
32/// name is spelled. Thus, the result shouldn't out-live that SourceManager.
33///
34/// This differs from Lexer::getImmediateMacroName in that any macro argument
35/// location will result in the topmost function macro that accepted it.
36/// e.g.
37/// \code
38///   MAC1( MAC2(foo) )
39/// \endcode
40/// for location of 'foo' token, this function will return "MAC1" while
41/// Lexer::getImmediateMacroName will return "MAC2".
42static StringRef getImmediateMacroName(SourceLocation Loc,
43                                       const SourceManager &SM,
44                                       const LangOptions &LangOpts) {
45   assert(Loc.isMacroID() && "Only reasonble to call this on macros");
46   // Walk past macro argument expanions.
47   while (SM.isMacroArgExpansion(Loc))
48     Loc = SM.getImmediateExpansionRange(Loc).first;
49
50   // If the macro's spelling has no FileID, then it's actually a token paste
51   // or stringization (or similar) and not a macro at all.
52   if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
53     return StringRef();
54
55   // Find the spelling location of the start of the non-argument expansion
56   // range. This is where the macro name was spelled in order to begin
57   // expanding this macro.
58   Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
59
60   // Dig out the buffer where the macro name was spelled and the extents of the
61   // name so that we can render it into the expansion note.
62   std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
63   unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
64   StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
65   return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
66}
67
68DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
69                                       DiagnosticOptions *DiagOpts)
70  : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
71
72DiagnosticRenderer::~DiagnosticRenderer() {}
73
74namespace {
75
76class FixitReceiver : public edit::EditsReceiver {
77  SmallVectorImpl<FixItHint> &MergedFixits;
78
79public:
80  FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
81    : MergedFixits(MergedFixits) { }
82  virtual void insert(SourceLocation loc, StringRef text) {
83    MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
84  }
85  virtual void replace(CharSourceRange range, StringRef text) {
86    MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
87  }
88};
89
90}
91
92static void mergeFixits(ArrayRef<FixItHint> FixItHints,
93                        const SourceManager &SM, const LangOptions &LangOpts,
94                        SmallVectorImpl<FixItHint> &MergedFixits) {
95  edit::Commit commit(SM, LangOpts);
96  for (ArrayRef<FixItHint>::const_iterator
97         I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
98    const FixItHint &Hint = *I;
99    if (Hint.CodeToInsert.empty()) {
100      if (Hint.InsertFromRange.isValid())
101        commit.insertFromRange(Hint.RemoveRange.getBegin(),
102                           Hint.InsertFromRange, /*afterToken=*/false,
103                           Hint.BeforePreviousInsertions);
104      else
105        commit.remove(Hint.RemoveRange);
106    } else {
107      if (Hint.RemoveRange.isTokenRange() ||
108          Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
109        commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
110      else
111        commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
112                    /*afterToken=*/false, Hint.BeforePreviousInsertions);
113    }
114  }
115
116  edit::EditedSource Editor(SM, LangOpts);
117  if (Editor.commit(commit)) {
118    FixitReceiver Rec(MergedFixits);
119    Editor.applyRewrites(Rec);
120  }
121}
122
123void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
124                                        DiagnosticsEngine::Level Level,
125                                        StringRef Message,
126                                        ArrayRef<CharSourceRange> Ranges,
127                                        ArrayRef<FixItHint> FixItHints,
128                                        const SourceManager *SM,
129                                        DiagOrStoredDiag D) {
130  assert(SM || Loc.isInvalid());
131
132  beginDiagnostic(D, Level);
133
134  if (!Loc.isValid())
135    // If we have no source location, just emit the diagnostic message.
136    emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D);
137  else {
138    // Get the ranges into a local array we can hack on.
139    SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
140                                                   Ranges.end());
141
142    SmallVector<FixItHint, 8> MergedFixits;
143    if (!FixItHints.empty()) {
144      mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
145      FixItHints = MergedFixits;
146    }
147
148    for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
149         E = FixItHints.end();
150         I != E; ++I)
151      if (I->RemoveRange.isValid())
152        MutableRanges.push_back(I->RemoveRange);
153
154    SourceLocation UnexpandedLoc = Loc;
155
156    // Find the ultimate expansion location for the diagnostic.
157    Loc = SM->getFileLoc(Loc);
158
159    PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
160
161    // First, if this diagnostic is not in the main file, print out the
162    // "included from" lines.
163    emitIncludeStack(Loc, PLoc, Level, *SM);
164
165    // Next, emit the actual diagnostic message and caret.
166    emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
167    emitCaret(Loc, Level, MutableRanges, FixItHints, *SM);
168
169    // If this location is within a macro, walk from UnexpandedLoc up to Loc
170    // and produce a macro backtrace.
171    if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
172      unsigned MacroDepth = 0;
173      emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM,
174                          MacroDepth);
175    }
176  }
177
178  LastLoc = Loc;
179  LastLevel = Level;
180
181  endDiagnostic(D, Level);
182}
183
184
185void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
186  emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
187                 Diag.getRanges(), Diag.getFixIts(),
188                 Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
189                                              : 0,
190                 &Diag);
191}
192
193/// \brief Prints an include stack when appropriate for a particular
194/// diagnostic level and location.
195///
196/// This routine handles all the logic of suppressing particular include
197/// stacks (such as those for notes) and duplicate include stacks when
198/// repeated warnings occur within the same file. It also handles the logic
199/// of customizing the formatting and display of the include stack.
200///
201/// \param Loc   The diagnostic location.
202/// \param PLoc  The presumed location of the diagnostic location.
203/// \param Level The diagnostic level of the message this stack pertains to.
204void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
205                                          PresumedLoc PLoc,
206                                          DiagnosticsEngine::Level Level,
207                                          const SourceManager &SM) {
208  SourceLocation IncludeLoc = PLoc.getIncludeLoc();
209
210  // Skip redundant include stacks altogether.
211  if (LastIncludeLoc == IncludeLoc)
212    return;
213
214  LastIncludeLoc = IncludeLoc;
215
216  if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
217    return;
218
219  if (IncludeLoc.isValid())
220    emitIncludeStackRecursively(IncludeLoc, SM);
221  else {
222    emitModuleBuildStack(SM);
223    emitImportStack(Loc, SM);
224  }
225}
226
227/// \brief Helper to recursivly walk up the include stack and print each layer
228/// on the way back down.
229void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
230                                                     const SourceManager &SM) {
231  if (Loc.isInvalid()) {
232    emitModuleBuildStack(SM);
233    return;
234  }
235
236  PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
237  if (PLoc.isInvalid())
238    return;
239
240  // If this source location was imported from a module, print the module
241  // import stack rather than the
242  // FIXME: We want submodule granularity here.
243  std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc);
244  if (Imported.first.isValid()) {
245    // This location was imported by a module. Emit the module import stack.
246    emitImportStackRecursively(Imported.first, Imported.second, SM);
247    return;
248  }
249
250  // Emit the other include frames first.
251  emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
252
253  // Emit the inclusion text/note.
254  emitIncludeLocation(Loc, PLoc, SM);
255}
256
257/// \brief Emit the module import stack associated with the current location.
258void DiagnosticRenderer::emitImportStack(SourceLocation Loc,
259                                         const SourceManager &SM) {
260  if (Loc.isInvalid()) {
261    emitModuleBuildStack(SM);
262    return;
263  }
264
265  std::pair<SourceLocation, StringRef> NextImportLoc
266    = SM.getModuleImportLoc(Loc);
267  emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
268}
269
270/// \brief Helper to recursivly walk up the import stack and print each layer
271/// on the way back down.
272void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
273                                                    StringRef ModuleName,
274                                                    const SourceManager &SM) {
275  if (Loc.isInvalid()) {
276    return;
277  }
278
279  PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
280  if (PLoc.isInvalid())
281    return;
282
283  // Emit the other import frames first.
284  std::pair<SourceLocation, StringRef> NextImportLoc
285    = SM.getModuleImportLoc(Loc);
286  emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
287
288  // Emit the inclusion text/note.
289  emitImportLocation(Loc, PLoc, ModuleName, SM);
290}
291
292/// \brief Emit the module build stack, for cases where a module is (re-)built
293/// on demand.
294void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
295  ModuleBuildStack Stack = SM.getModuleBuildStack();
296  for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
297    const SourceManager &CurSM = Stack[I].second.getManager();
298    SourceLocation CurLoc = Stack[I].second;
299    emitBuildingModuleLocation(CurLoc,
300                               CurSM.getPresumedLoc(CurLoc,
301                                                    DiagOpts->ShowPresumedLoc),
302                               Stack[I].first,
303                               CurSM);
304  }
305}
306
307// Helper function to fix up source ranges.  It takes in an array of ranges,
308// and outputs an array of ranges where we want to draw the range highlighting
309// around the location specified by CaretLoc.
310//
311// To find locations which correspond to the caret, we crawl the macro caller
312// chain for the beginning and end of each range.  If the caret location
313// is in a macro expansion, we search each chain for a location
314// in the same expansion as the caret; otherwise, we crawl to the top of
315// each chain. Two locations are part of the same macro expansion
316// iff the FileID is the same.
317static void mapDiagnosticRanges(
318    SourceLocation CaretLoc,
319    ArrayRef<CharSourceRange> Ranges,
320    SmallVectorImpl<CharSourceRange> &SpellingRanges,
321    const SourceManager *SM) {
322  FileID CaretLocFileID = SM->getFileID(CaretLoc);
323
324  for (ArrayRef<CharSourceRange>::const_iterator I = Ranges.begin(),
325       E = Ranges.end();
326       I != E; ++I) {
327    SourceLocation Begin = I->getBegin(), End = I->getEnd();
328    bool IsTokenRange = I->isTokenRange();
329
330    FileID BeginFileID = SM->getFileID(Begin);
331    FileID EndFileID = SM->getFileID(End);
332
333    // Find the common parent for the beginning and end of the range.
334
335    // First, crawl the expansion chain for the beginning of the range.
336    llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
337    while (Begin.isMacroID() && BeginFileID != EndFileID) {
338      BeginLocsMap[BeginFileID] = Begin;
339      Begin = SM->getImmediateExpansionRange(Begin).first;
340      BeginFileID = SM->getFileID(Begin);
341    }
342
343    // Then, crawl the expansion chain for the end of the range.
344    if (BeginFileID != EndFileID) {
345      while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
346        End = SM->getImmediateExpansionRange(End).second;
347        EndFileID = SM->getFileID(End);
348      }
349      if (End.isMacroID()) {
350        Begin = BeginLocsMap[EndFileID];
351        BeginFileID = EndFileID;
352      }
353    }
354
355    while (Begin.isMacroID() && BeginFileID != CaretLocFileID) {
356      if (SM->isMacroArgExpansion(Begin)) {
357        Begin = SM->getImmediateSpellingLoc(Begin);
358        End = SM->getImmediateSpellingLoc(End);
359      } else {
360        Begin = SM->getImmediateExpansionRange(Begin).first;
361        End = SM->getImmediateExpansionRange(End).second;
362      }
363      BeginFileID = SM->getFileID(Begin);
364      if (BeginFileID != SM->getFileID(End)) {
365        // FIXME: Ugly hack to stop a crash; this code is making bad
366        // assumptions and it's too complicated for me to reason
367        // about.
368        Begin = End = SourceLocation();
369        break;
370      }
371    }
372
373    // Return the spelling location of the beginning and end of the range.
374    Begin = SM->getSpellingLoc(Begin);
375    End = SM->getSpellingLoc(End);
376    SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
377                                             IsTokenRange));
378  }
379}
380
381void DiagnosticRenderer::emitCaret(SourceLocation Loc,
382                                   DiagnosticsEngine::Level Level,
383                                   ArrayRef<CharSourceRange> Ranges,
384                                   ArrayRef<FixItHint> Hints,
385                                   const SourceManager &SM) {
386  SmallVector<CharSourceRange, 4> SpellingRanges;
387  mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
388  emitCodeContext(Loc, Level, SpellingRanges, Hints, SM);
389}
390
391/// \brief Recursively emit notes for each macro expansion and caret
392/// diagnostics where appropriate.
393///
394/// Walks up the macro expansion stack printing expansion notes, the code
395/// snippet, caret, underlines and FixItHint display as appropriate at each
396/// level.
397///
398/// \param Loc The location for this caret.
399/// \param Level The diagnostic level currently being emitted.
400/// \param Ranges The underlined ranges for this code snippet.
401/// \param Hints The FixIt hints active for this diagnostic.
402/// \param OnMacroInst The current depth of the macro expansion stack.
403void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc,
404                                             DiagnosticsEngine::Level Level,
405                                             ArrayRef<CharSourceRange> Ranges,
406                                             ArrayRef<FixItHint> Hints,
407                                             const SourceManager &SM,
408                                             unsigned &MacroDepth,
409                                             unsigned OnMacroInst) {
410  assert(!Loc.isInvalid() && "must have a valid source location here");
411
412  // Walk up to the caller of this macro, and produce a backtrace down to there.
413  SourceLocation OneLevelUp = SM.getImmediateMacroCallerLoc(Loc);
414  if (OneLevelUp.isMacroID())
415    emitMacroExpansions(OneLevelUp, Level, Ranges, Hints, SM,
416                        MacroDepth, OnMacroInst + 1);
417  else
418    MacroDepth = OnMacroInst + 1;
419
420  unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
421  if (MacroDepth > DiagOpts->MacroBacktraceLimit &&
422      DiagOpts->MacroBacktraceLimit != 0) {
423    MacroSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
424    DiagOpts->MacroBacktraceLimit % 2;
425    MacroSkipEnd = MacroDepth - DiagOpts->MacroBacktraceLimit / 2;
426  }
427
428  // Whether to suppress printing this macro expansion.
429  bool Suppressed = (OnMacroInst >= MacroSkipStart &&
430                     OnMacroInst < MacroSkipEnd);
431
432  if (Suppressed) {
433    // Tell the user that we've skipped contexts.
434    if (OnMacroInst == MacroSkipStart) {
435      SmallString<200> MessageStorage;
436      llvm::raw_svector_ostream Message(MessageStorage);
437      Message << "(skipping " << (MacroSkipEnd - MacroSkipStart)
438              << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
439                 "see all)";
440      emitBasicNote(Message.str());
441    }
442    return;
443  }
444
445  // Find the spelling location for the macro definition. We must use the
446  // spelling location here to avoid emitting a macro bactrace for the note.
447  SourceLocation SpellingLoc = Loc;
448  // If this is the expansion of a macro argument, point the caret at the
449  // use of the argument in the definition of the macro, not the expansion.
450  if (SM.isMacroArgExpansion(Loc))
451    SpellingLoc = SM.getImmediateExpansionRange(Loc).first;
452  SpellingLoc = SM.getSpellingLoc(SpellingLoc);
453
454  // Map the ranges into the FileID of the diagnostic location.
455  SmallVector<CharSourceRange, 4> SpellingRanges;
456  mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
457
458  SmallString<100> MessageStorage;
459  llvm::raw_svector_ostream Message(MessageStorage);
460  StringRef MacroName = getImmediateMacroName(Loc, SM, LangOpts);
461  if (MacroName.empty())
462    Message << "expanded from here";
463  else
464    Message << "expanded from macro '" << MacroName << "'";
465  emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
466                 SpellingRanges, None, &SM);
467}
468
469DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
470
471void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
472                                                 PresumedLoc PLoc,
473                                                 const SourceManager &SM) {
474  // Generate a note indicating the include location.
475  SmallString<200> MessageStorage;
476  llvm::raw_svector_ostream Message(MessageStorage);
477  Message << "in file included from " << PLoc.getFilename() << ':'
478          << PLoc.getLine() << ":";
479  emitNote(Loc, Message.str(), &SM);
480}
481
482void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc,
483                                                PresumedLoc PLoc,
484                                                StringRef ModuleName,
485                                                const SourceManager &SM) {
486  // Generate a note indicating the include location.
487  SmallString<200> MessageStorage;
488  llvm::raw_svector_ostream Message(MessageStorage);
489  Message << "in module '" << ModuleName << "' imported from "
490          << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
491  emitNote(Loc, Message.str(), &SM);
492}
493
494void
495DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc,
496                                                   PresumedLoc PLoc,
497                                                   StringRef ModuleName,
498                                                   const SourceManager &SM) {
499  // Generate a note indicating the include location.
500  SmallString<200> MessageStorage;
501  llvm::raw_svector_ostream Message(MessageStorage);
502  Message << "while building module '" << ModuleName << "' imported from "
503          << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
504  emitNote(Loc, Message.str(), &SM);
505}
506
507
508void DiagnosticNoteRenderer::emitBasicNote(StringRef Message) {
509  emitNote(SourceLocation(), Message, 0);
510}
511