clang API Documentation

DiagnosticRenderer.cpp
Go to the documentation of this file.
00001 //===--- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/Frontend/DiagnosticRenderer.h"
00011 #include "clang/Basic/DiagnosticOptions.h"
00012 #include "clang/Basic/FileManager.h"
00013 #include "clang/Basic/SourceManager.h"
00014 #include "clang/Edit/Commit.h"
00015 #include "clang/Edit/EditedSource.h"
00016 #include "clang/Edit/EditsReceiver.h"
00017 #include "clang/Lex/Lexer.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/Support/ErrorHandling.h"
00021 #include "llvm/Support/MemoryBuffer.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 #include <algorithm>
00024 using namespace clang;
00025 
00026 /// \brief Retrieve the name of the immediate macro expansion.
00027 ///
00028 /// This routine starts from a source location, and finds the name of the macro
00029 /// responsible for its immediate expansion. It looks through any intervening
00030 /// macro argument expansions to compute this. It returns a StringRef which
00031 /// refers to the SourceManager-owned buffer of the source where that macro
00032 /// name is spelled. Thus, the result shouldn't out-live that SourceManager.
00033 ///
00034 /// This differs from Lexer::getImmediateMacroName in that any macro argument
00035 /// location will result in the topmost function macro that accepted it.
00036 /// e.g.
00037 /// \code
00038 ///   MAC1( MAC2(foo) )
00039 /// \endcode
00040 /// for location of 'foo' token, this function will return "MAC1" while
00041 /// Lexer::getImmediateMacroName will return "MAC2".
00042 static StringRef getImmediateMacroName(SourceLocation Loc,
00043                                        const SourceManager &SM,
00044                                        const LangOptions &LangOpts) {
00045    assert(Loc.isMacroID() && "Only reasonble to call this on macros");
00046    // Walk past macro argument expanions.
00047    while (SM.isMacroArgExpansion(Loc))
00048      Loc = SM.getImmediateExpansionRange(Loc).first;
00049 
00050    // If the macro's spelling has no FileID, then it's actually a token paste
00051    // or stringization (or similar) and not a macro at all.
00052    if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
00053      return StringRef();
00054 
00055    // Find the spelling location of the start of the non-argument expansion
00056    // range. This is where the macro name was spelled in order to begin
00057    // expanding this macro.
00058    Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
00059 
00060    // Dig out the buffer where the macro name was spelled and the extents of the
00061    // name so that we can render it into the expansion note.
00062    std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
00063    unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
00064    StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
00065    return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
00066 }
00067 
00068 DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
00069                                        DiagnosticOptions *DiagOpts)
00070   : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
00071 
00072 DiagnosticRenderer::~DiagnosticRenderer() {}
00073 
00074 namespace {
00075 
00076 class FixitReceiver : public edit::EditsReceiver {
00077   SmallVectorImpl<FixItHint> &MergedFixits;
00078 
00079 public:
00080   FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
00081     : MergedFixits(MergedFixits) { }
00082   void insert(SourceLocation loc, StringRef text) override {
00083     MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
00084   }
00085   void replace(CharSourceRange range, StringRef text) override {
00086     MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
00087   }
00088 };
00089 
00090 }
00091 
00092 static void mergeFixits(ArrayRef<FixItHint> FixItHints,
00093                         const SourceManager &SM, const LangOptions &LangOpts,
00094                         SmallVectorImpl<FixItHint> &MergedFixits) {
00095   edit::Commit commit(SM, LangOpts);
00096   for (ArrayRef<FixItHint>::const_iterator
00097          I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
00098     const FixItHint &Hint = *I;
00099     if (Hint.CodeToInsert.empty()) {
00100       if (Hint.InsertFromRange.isValid())
00101         commit.insertFromRange(Hint.RemoveRange.getBegin(),
00102                            Hint.InsertFromRange, /*afterToken=*/false,
00103                            Hint.BeforePreviousInsertions);
00104       else
00105         commit.remove(Hint.RemoveRange);
00106     } else {
00107       if (Hint.RemoveRange.isTokenRange() ||
00108           Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
00109         commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
00110       else
00111         commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
00112                     /*afterToken=*/false, Hint.BeforePreviousInsertions);
00113     }
00114   }
00115 
00116   edit::EditedSource Editor(SM, LangOpts);
00117   if (Editor.commit(commit)) {
00118     FixitReceiver Rec(MergedFixits);
00119     Editor.applyRewrites(Rec);
00120   }
00121 }
00122 
00123 void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
00124                                         DiagnosticsEngine::Level Level,
00125                                         StringRef Message,
00126                                         ArrayRef<CharSourceRange> Ranges,
00127                                         ArrayRef<FixItHint> FixItHints,
00128                                         const SourceManager *SM,
00129                                         DiagOrStoredDiag D) {
00130   assert(SM || Loc.isInvalid());
00131 
00132   beginDiagnostic(D, Level);
00133 
00134   if (!Loc.isValid())
00135     // If we have no source location, just emit the diagnostic message.
00136     emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D);
00137   else {
00138     // Get the ranges into a local array we can hack on.
00139     SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
00140                                                    Ranges.end());
00141 
00142     SmallVector<FixItHint, 8> MergedFixits;
00143     if (!FixItHints.empty()) {
00144       mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
00145       FixItHints = MergedFixits;
00146     }
00147 
00148     for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
00149          E = FixItHints.end();
00150          I != E; ++I)
00151       if (I->RemoveRange.isValid())
00152         MutableRanges.push_back(I->RemoveRange);
00153 
00154     SourceLocation UnexpandedLoc = Loc;
00155 
00156     // Find the ultimate expansion location for the diagnostic.
00157     Loc = SM->getFileLoc(Loc);
00158 
00159     PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
00160 
00161     // First, if this diagnostic is not in the main file, print out the
00162     // "included from" lines.
00163     emitIncludeStack(Loc, PLoc, Level, *SM);
00164 
00165     // Next, emit the actual diagnostic message and caret.
00166     emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
00167     emitCaret(Loc, Level, MutableRanges, FixItHints, *SM);
00168 
00169     // If this location is within a macro, walk from UnexpandedLoc up to Loc
00170     // and produce a macro backtrace.
00171     if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
00172       unsigned MacroDepth = 0;
00173       emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM,
00174                           MacroDepth);
00175     }
00176   }
00177 
00178   LastLoc = Loc;
00179   LastLevel = Level;
00180 
00181   endDiagnostic(D, Level);
00182 }
00183 
00184 
00185 void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
00186   emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
00187                  Diag.getRanges(), Diag.getFixIts(),
00188                  Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
00189                                               : nullptr,
00190                  &Diag);
00191 }
00192 
00193 void DiagnosticRenderer::emitBasicNote(StringRef Message) {
00194   emitDiagnosticMessage(
00195       SourceLocation(), PresumedLoc(), DiagnosticsEngine::Note, Message,
00196       None, nullptr, DiagOrStoredDiag());
00197 }
00198 
00199 /// \brief Prints an include stack when appropriate for a particular
00200 /// diagnostic level and location.
00201 ///
00202 /// This routine handles all the logic of suppressing particular include
00203 /// stacks (such as those for notes) and duplicate include stacks when
00204 /// repeated warnings occur within the same file. It also handles the logic
00205 /// of customizing the formatting and display of the include stack.
00206 ///
00207 /// \param Loc   The diagnostic location.
00208 /// \param PLoc  The presumed location of the diagnostic location.
00209 /// \param Level The diagnostic level of the message this stack pertains to.
00210 void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
00211                                           PresumedLoc PLoc,
00212                                           DiagnosticsEngine::Level Level,
00213                                           const SourceManager &SM) {
00214   SourceLocation IncludeLoc = PLoc.getIncludeLoc();
00215 
00216   // Skip redundant include stacks altogether.
00217   if (LastIncludeLoc == IncludeLoc)
00218     return;
00219   
00220   LastIncludeLoc = IncludeLoc;
00221   
00222   if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
00223     return;
00224 
00225   if (IncludeLoc.isValid())
00226     emitIncludeStackRecursively(IncludeLoc, SM);
00227   else {
00228     emitModuleBuildStack(SM);
00229     emitImportStack(Loc, SM);
00230   }
00231 }
00232 
00233 /// \brief Helper to recursivly walk up the include stack and print each layer
00234 /// on the way back down.
00235 void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
00236                                                      const SourceManager &SM) {
00237   if (Loc.isInvalid()) {
00238     emitModuleBuildStack(SM);
00239     return;
00240   }
00241   
00242   PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
00243   if (PLoc.isInvalid())
00244     return;
00245 
00246   // If this source location was imported from a module, print the module
00247   // import stack rather than the 
00248   // FIXME: We want submodule granularity here.
00249   std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc);
00250   if (Imported.first.isValid()) {
00251     // This location was imported by a module. Emit the module import stack.
00252     emitImportStackRecursively(Imported.first, Imported.second, SM);
00253     return;
00254   }
00255 
00256   // Emit the other include frames first.
00257   emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
00258   
00259   // Emit the inclusion text/note.
00260   emitIncludeLocation(Loc, PLoc, SM);
00261 }
00262 
00263 /// \brief Emit the module import stack associated with the current location.
00264 void DiagnosticRenderer::emitImportStack(SourceLocation Loc,
00265                                          const SourceManager &SM) {
00266   if (Loc.isInvalid()) {
00267     emitModuleBuildStack(SM);
00268     return;
00269   }
00270 
00271   std::pair<SourceLocation, StringRef> NextImportLoc
00272     = SM.getModuleImportLoc(Loc);
00273   emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
00274 }
00275 
00276 /// \brief Helper to recursivly walk up the import stack and print each layer
00277 /// on the way back down.
00278 void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
00279                                                     StringRef ModuleName,
00280                                                     const SourceManager &SM) {
00281   if (Loc.isInvalid()) {
00282     return;
00283   }
00284 
00285   PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
00286   if (PLoc.isInvalid())
00287     return;
00288 
00289   // Emit the other import frames first.
00290   std::pair<SourceLocation, StringRef> NextImportLoc
00291     = SM.getModuleImportLoc(Loc);
00292   emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
00293 
00294   // Emit the inclusion text/note.
00295   emitImportLocation(Loc, PLoc, ModuleName, SM);
00296 }
00297 
00298 /// \brief Emit the module build stack, for cases where a module is (re-)built
00299 /// on demand.
00300 void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
00301   ModuleBuildStack Stack = SM.getModuleBuildStack();
00302   for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
00303     const SourceManager &CurSM = Stack[I].second.getManager();
00304     SourceLocation CurLoc = Stack[I].second;
00305     emitBuildingModuleLocation(CurLoc,
00306                                CurSM.getPresumedLoc(CurLoc,
00307                                                     DiagOpts->ShowPresumedLoc),
00308                                Stack[I].first,
00309                                CurSM);
00310   }
00311 }
00312 
00313 // Helper function to fix up source ranges.  It takes in an array of ranges,
00314 // and outputs an array of ranges where we want to draw the range highlighting
00315 // around the location specified by CaretLoc.
00316 //
00317 // To find locations which correspond to the caret, we crawl the macro caller
00318 // chain for the beginning and end of each range.  If the caret location
00319 // is in a macro expansion, we search each chain for a location
00320 // in the same expansion as the caret; otherwise, we crawl to the top of
00321 // each chain. Two locations are part of the same macro expansion
00322 // iff the FileID is the same.
00323 static void mapDiagnosticRanges(
00324     SourceLocation CaretLoc,
00325     ArrayRef<CharSourceRange> Ranges,
00326     SmallVectorImpl<CharSourceRange> &SpellingRanges,
00327     const SourceManager *SM) {
00328   FileID CaretLocFileID = SM->getFileID(CaretLoc);
00329 
00330   for (ArrayRef<CharSourceRange>::const_iterator I = Ranges.begin(),
00331        E = Ranges.end();
00332        I != E; ++I) {
00333     SourceLocation Begin = I->getBegin(), End = I->getEnd();
00334     bool IsTokenRange = I->isTokenRange();
00335 
00336     FileID BeginFileID = SM->getFileID(Begin);
00337     FileID EndFileID = SM->getFileID(End);
00338 
00339     // Find the common parent for the beginning and end of the range.
00340 
00341     // First, crawl the expansion chain for the beginning of the range.
00342     llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
00343     while (Begin.isMacroID() && BeginFileID != EndFileID) {
00344       BeginLocsMap[BeginFileID] = Begin;
00345       Begin = SM->getImmediateExpansionRange(Begin).first;
00346       BeginFileID = SM->getFileID(Begin);
00347     }
00348 
00349     // Then, crawl the expansion chain for the end of the range.
00350     if (BeginFileID != EndFileID) {
00351       while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
00352         End = SM->getImmediateExpansionRange(End).second;
00353         EndFileID = SM->getFileID(End);
00354       }
00355       if (End.isMacroID()) {
00356         Begin = BeginLocsMap[EndFileID];
00357         BeginFileID = EndFileID;
00358       }
00359     }
00360 
00361     while (Begin.isMacroID() && BeginFileID != CaretLocFileID) {
00362       if (SM->isMacroArgExpansion(Begin)) {
00363         Begin = SM->getImmediateSpellingLoc(Begin);
00364         End = SM->getImmediateSpellingLoc(End);
00365       } else {
00366         Begin = SM->getImmediateExpansionRange(Begin).first;
00367         End = SM->getImmediateExpansionRange(End).second;
00368       }
00369       BeginFileID = SM->getFileID(Begin);
00370       if (BeginFileID != SM->getFileID(End)) {
00371         // FIXME: Ugly hack to stop a crash; this code is making bad
00372         // assumptions and it's too complicated for me to reason
00373         // about.
00374         Begin = End = SourceLocation();
00375         break;
00376       }
00377     }
00378 
00379     // Return the spelling location of the beginning and end of the range.
00380     Begin = SM->getSpellingLoc(Begin);
00381     End = SM->getSpellingLoc(End);
00382     SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
00383                                              IsTokenRange));
00384   }
00385 }
00386 
00387 void DiagnosticRenderer::emitCaret(SourceLocation Loc,
00388                                    DiagnosticsEngine::Level Level,
00389                                    ArrayRef<CharSourceRange> Ranges,
00390                                    ArrayRef<FixItHint> Hints,
00391                                    const SourceManager &SM) {
00392   SmallVector<CharSourceRange, 4> SpellingRanges;
00393   mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
00394   emitCodeContext(Loc, Level, SpellingRanges, Hints, SM);
00395 }
00396 
00397 /// \brief Recursively emit notes for each macro expansion and caret
00398 /// diagnostics where appropriate.
00399 ///
00400 /// Walks up the macro expansion stack printing expansion notes, the code
00401 /// snippet, caret, underlines and FixItHint display as appropriate at each
00402 /// level.
00403 ///
00404 /// \param Loc The location for this caret.
00405 /// \param Level The diagnostic level currently being emitted.
00406 /// \param Ranges The underlined ranges for this code snippet.
00407 /// \param Hints The FixIt hints active for this diagnostic.
00408 /// \param OnMacroInst The current depth of the macro expansion stack.
00409 void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc,
00410                                              DiagnosticsEngine::Level Level,
00411                                              ArrayRef<CharSourceRange> Ranges,
00412                                              ArrayRef<FixItHint> Hints,
00413                                              const SourceManager &SM,
00414                                              unsigned &MacroDepth,
00415                                              unsigned OnMacroInst) {
00416   assert(!Loc.isInvalid() && "must have a valid source location here");
00417 
00418   // Walk up to the caller of this macro, and produce a backtrace down to there.
00419   SourceLocation OneLevelUp = SM.getImmediateMacroCallerLoc(Loc);
00420   if (OneLevelUp.isMacroID())
00421     emitMacroExpansions(OneLevelUp, Level, Ranges, Hints, SM,
00422                         MacroDepth, OnMacroInst + 1);
00423   else
00424     MacroDepth = OnMacroInst + 1;
00425 
00426   unsigned MacroSkipStart = 0, MacroSkipEnd = 0;
00427   if (MacroDepth > DiagOpts->MacroBacktraceLimit &&
00428       DiagOpts->MacroBacktraceLimit != 0) {
00429     MacroSkipStart = DiagOpts->MacroBacktraceLimit / 2 +
00430     DiagOpts->MacroBacktraceLimit % 2;
00431     MacroSkipEnd = MacroDepth - DiagOpts->MacroBacktraceLimit / 2;
00432   }
00433 
00434   // Whether to suppress printing this macro expansion.
00435   bool Suppressed = (OnMacroInst >= MacroSkipStart &&
00436                      OnMacroInst < MacroSkipEnd);
00437 
00438   if (Suppressed) {
00439     // Tell the user that we've skipped contexts.
00440     if (OnMacroInst == MacroSkipStart) {
00441       SmallString<200> MessageStorage;
00442       llvm::raw_svector_ostream Message(MessageStorage);
00443       Message << "(skipping " << (MacroSkipEnd - MacroSkipStart)
00444               << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
00445                  "see all)";
00446       emitBasicNote(Message.str());      
00447     }
00448     return;
00449   }
00450 
00451   // Find the spelling location for the macro definition. We must use the
00452   // spelling location here to avoid emitting a macro bactrace for the note.
00453   SourceLocation SpellingLoc = Loc;
00454   // If this is the expansion of a macro argument, point the caret at the
00455   // use of the argument in the definition of the macro, not the expansion.
00456   if (SM.isMacroArgExpansion(Loc))
00457     SpellingLoc = SM.getImmediateExpansionRange(Loc).first;
00458   SpellingLoc = SM.getSpellingLoc(SpellingLoc);
00459 
00460   // Map the ranges into the FileID of the diagnostic location.
00461   SmallVector<CharSourceRange, 4> SpellingRanges;
00462   mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
00463 
00464   SmallString<100> MessageStorage;
00465   llvm::raw_svector_ostream Message(MessageStorage);
00466   StringRef MacroName = getImmediateMacroName(Loc, SM, LangOpts);
00467   if (MacroName.empty())
00468     Message << "expanded from here";
00469   else
00470     Message << "expanded from macro '" << MacroName << "'";
00471   emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
00472                  SpellingRanges, None, &SM);
00473 }
00474 
00475 DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
00476 
00477 void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
00478                                                  PresumedLoc PLoc,
00479                                                  const SourceManager &SM) {
00480   // Generate a note indicating the include location.
00481   SmallString<200> MessageStorage;
00482   llvm::raw_svector_ostream Message(MessageStorage);
00483   Message << "in file included from " << PLoc.getFilename() << ':'
00484           << PLoc.getLine() << ":";
00485   emitNote(Loc, Message.str(), &SM);
00486 }
00487 
00488 void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc,
00489                                                 PresumedLoc PLoc,
00490                                                 StringRef ModuleName,
00491                                                 const SourceManager &SM) {
00492   // Generate a note indicating the include location.
00493   SmallString<200> MessageStorage;
00494   llvm::raw_svector_ostream Message(MessageStorage);
00495   Message << "in module '" << ModuleName << "' imported from "
00496           << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
00497   emitNote(Loc, Message.str(), &SM);
00498 }
00499 
00500 void
00501 DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc,
00502                                                    PresumedLoc PLoc,
00503                                                    StringRef ModuleName,
00504                                                    const SourceManager &SM) {
00505   // Generate a note indicating the include location.
00506   SmallString<200> MessageStorage;
00507   llvm::raw_svector_ostream Message(MessageStorage);
00508   if (PLoc.getFilename())
00509     Message << "while building module '" << ModuleName << "' imported from "
00510             << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
00511   else
00512     Message << "while building module '" << ModuleName << "':";
00513   emitNote(Loc, Message.str(), &SM);
00514 }