//===--- PlistDiagnostics.cpp - Plist Diagnostics for Paths -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PlistDiagnostics object. // //===----------------------------------------------------------------------===// #include "clang/Basic/FileManager.h" #include "clang/Basic/PlistSupport.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Version.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/TokenConcatenation.h" #include "clang/Rewrite/Core/HTMLRewrite.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include "clang/StaticAnalyzer/Core/IssueHash.h" #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" using namespace clang; using namespace ento; using namespace markup; //===----------------------------------------------------------------------===// // Declarations of helper classes and functions for emitting bug reports in // plist format. //===----------------------------------------------------------------------===// namespace { class PlistDiagnostics : public PathDiagnosticConsumer { const std::string OutputFile; const Preprocessor &PP; AnalyzerOptions &AnOpts; const bool SupportsCrossFileDiagnostics; public: PlistDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string& prefix, const Preprocessor &PP, bool supportsMultipleFiles); ~PlistDiagnostics() override {} void FlushDiagnosticsImpl(std::vector &Diags, FilesMade *filesMade) override; StringRef getName() const override { return "PlistDiagnostics"; } PathGenerationScheme getGenerationScheme() const override { return Extensive; } bool supportsLogicalOpControlFlow() const override { return true; } bool supportsCrossFileDiagnostics() const override { return SupportsCrossFileDiagnostics; } }; } // end anonymous namespace namespace { /// A helper class for emitting a single report. class PlistPrinter { const FIDMap& FM; AnalyzerOptions &AnOpts; const Preprocessor &PP; llvm::SmallVector MacroPieces; public: PlistPrinter(const FIDMap& FM, AnalyzerOptions &AnOpts, const Preprocessor &PP) : FM(FM), AnOpts(AnOpts), PP(PP) { } void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) { ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true); // Don't emit a warning about an unused private field. (void)AnOpts; } /// Print the expansions of the collected macro pieces. /// /// Each time ReportDiag is called on a PathDiagnosticMacroPiece (or, if one /// is found through a call piece, etc), it's subpieces are reported, and the /// piece itself is collected. Call this function after the entire bugpath /// was reported. void ReportMacroExpansions(raw_ostream &o, unsigned indent); private: void ReportPiece(raw_ostream &o, const PathDiagnosticPiece &P, unsigned indent, unsigned depth, bool includeControlFlow, bool isKeyEvent = false) { switch (P.getKind()) { case PathDiagnosticPiece::ControlFlow: if (includeControlFlow) ReportControlFlow(o, cast(P), indent); break; case PathDiagnosticPiece::Call: ReportCall(o, cast(P), indent, depth); break; case PathDiagnosticPiece::Event: ReportEvent(o, cast(P), indent, depth, isKeyEvent); break; case PathDiagnosticPiece::Macro: ReportMacroSubPieces(o, cast(P), indent, depth); break; case PathDiagnosticPiece::Note: ReportNote(o, cast(P), indent); break; } } void EmitRanges(raw_ostream &o, const ArrayRef Ranges, unsigned indent); void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent); void ReportControlFlow(raw_ostream &o, const PathDiagnosticControlFlowPiece& P, unsigned indent); void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P, unsigned indent, unsigned depth, bool isKeyEvent = false); void ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P, unsigned indent, unsigned depth); void ReportMacroSubPieces(raw_ostream &o, const PathDiagnosticMacroPiece& P, unsigned indent, unsigned depth); void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P, unsigned indent); }; } // end of anonymous namespace namespace { struct ExpansionInfo { std::string MacroName; std::string Expansion; ExpansionInfo(std::string N, std::string E) : MacroName(std::move(N)), Expansion(std::move(E)) {} }; } // end of anonymous namespace static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM, AnalyzerOptions &AnOpts, const Preprocessor &PP, const PathPieces &Path); /// Print coverage information to output stream {@code o}. /// May modify the used list of files {@code Fids} by inserting new ones. static void printCoverage(const PathDiagnostic *D, unsigned InputIndentLevel, SmallVectorImpl &Fids, FIDMap &FM, llvm::raw_fd_ostream &o); static ExpansionInfo getExpandedMacro(SourceLocation MacroLoc, const Preprocessor &PP); //===----------------------------------------------------------------------===// // Methods of PlistPrinter. //===----------------------------------------------------------------------===// void PlistPrinter::EmitRanges(raw_ostream &o, const ArrayRef Ranges, unsigned indent) { if (Ranges.empty()) return; Indent(o, indent) << "ranges\n"; Indent(o, indent) << "\n"; ++indent; const SourceManager &SM = PP.getSourceManager(); const LangOptions &LangOpts = PP.getLangOpts(); for (auto &R : Ranges) EmitRange(o, SM, Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts), FM, indent + 1); --indent; Indent(o, indent) << "\n"; } void PlistPrinter::EmitMessage(raw_ostream &o, StringRef Message, unsigned indent) { // Output the text. assert(!Message.empty()); Indent(o, indent) << "extended_message\n"; Indent(o, indent); EmitString(o, Message) << '\n'; // Output the short text. // FIXME: Really use a short string. Indent(o, indent) << "message\n"; Indent(o, indent); EmitString(o, Message) << '\n'; } void PlistPrinter::ReportControlFlow(raw_ostream &o, const PathDiagnosticControlFlowPiece& P, unsigned indent) { const SourceManager &SM = PP.getSourceManager(); const LangOptions &LangOpts = PP.getLangOpts(); Indent(o, indent) << "\n"; ++indent; Indent(o, indent) << "kindcontrol\n"; // Emit edges. Indent(o, indent) << "edges\n"; ++indent; Indent(o, indent) << "\n"; ++indent; for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end(); I!=E; ++I) { Indent(o, indent) << "\n"; ++indent; // Make the ranges of the start and end point self-consistent with adjacent edges // by forcing to use only the beginning of the range. This simplifies the layout // logic for clients. Indent(o, indent) << "start\n"; SourceRange StartEdge( SM.getExpansionLoc(I->getStart().asRange().getBegin())); EmitRange(o, SM, Lexer::getAsCharRange(StartEdge, SM, LangOpts), FM, indent + 1); Indent(o, indent) << "end\n"; SourceRange EndEdge(SM.getExpansionLoc(I->getEnd().asRange().getBegin())); EmitRange(o, SM, Lexer::getAsCharRange(EndEdge, SM, LangOpts), FM, indent + 1); --indent; Indent(o, indent) << "\n"; } --indent; Indent(o, indent) << "\n"; --indent; // Output any helper text. const auto &s = P.getString(); if (!s.empty()) { Indent(o, indent) << "alternate"; EmitString(o, s) << '\n'; } --indent; Indent(o, indent) << "\n"; } void PlistPrinter::ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P, unsigned indent, unsigned depth, bool isKeyEvent) { const SourceManager &SM = PP.getSourceManager(); Indent(o, indent) << "\n"; ++indent; Indent(o, indent) << "kindevent\n"; if (isKeyEvent) { Indent(o, indent) << "key_event\n"; } // Output the location. FullSourceLoc L = P.getLocation().asLocation(); Indent(o, indent) << "location\n"; EmitLocation(o, SM, L, FM, indent); // Output the ranges (if any). ArrayRef Ranges = P.getRanges(); EmitRanges(o, Ranges, indent); // Output the call depth. Indent(o, indent) << "depth"; EmitInteger(o, depth) << '\n'; // Output the text. EmitMessage(o, P.getString(), indent); // Finish up. --indent; Indent(o, indent); o << "\n"; } void PlistPrinter::ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P, unsigned indent, unsigned depth) { if (auto callEnter = P.getCallEnterEvent()) ReportPiece(o, *callEnter, indent, depth, /*includeControlFlow*/ true, P.isLastInMainSourceFile()); ++depth; if (auto callEnterWithinCaller = P.getCallEnterWithinCallerEvent()) ReportPiece(o, *callEnterWithinCaller, indent, depth, /*includeControlFlow*/ true); for (PathPieces::const_iterator I = P.path.begin(), E = P.path.end();I!=E;++I) ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ true); --depth; if (auto callExit = P.getCallExitEvent()) ReportPiece(o, *callExit, indent, depth, /*includeControlFlow*/ true); } void PlistPrinter::ReportMacroSubPieces(raw_ostream &o, const PathDiagnosticMacroPiece& P, unsigned indent, unsigned depth) { MacroPieces.push_back(&P); for (PathPieces::const_iterator I = P.subPieces.begin(), E = P.subPieces.end(); I != E; ++I) { ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ false); } } void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) { for (const PathDiagnosticMacroPiece *P : MacroPieces) { const SourceManager &SM = PP.getSourceManager(); ExpansionInfo EI = getExpandedMacro(P->getLocation().asLocation(), PP); Indent(o, indent) << "\n"; ++indent; // Output the location. FullSourceLoc L = P->getLocation().asLocation(); Indent(o, indent) << "location\n"; EmitLocation(o, SM, L, FM, indent); // Output the ranges (if any). ArrayRef Ranges = P->getRanges(); EmitRanges(o, Ranges, indent); // Output the macro name. Indent(o, indent) << "name"; EmitString(o, EI.MacroName) << '\n'; // Output what it expands into. Indent(o, indent) << "expansion"; EmitString(o, EI.Expansion) << '\n'; // Finish up. --indent; Indent(o, indent); o << "\n"; } } void PlistPrinter::ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P, unsigned indent) { const SourceManager &SM = PP.getSourceManager(); Indent(o, indent) << "\n"; ++indent; // Output the location. FullSourceLoc L = P.getLocation().asLocation(); Indent(o, indent) << "location\n"; EmitLocation(o, SM, L, FM, indent); // Output the ranges (if any). ArrayRef Ranges = P.getRanges(); EmitRanges(o, Ranges, indent); // Output the text. EmitMessage(o, P.getString(), indent); // Finish up. --indent; Indent(o, indent); o << "\n"; } //===----------------------------------------------------------------------===// // Static function definitions. //===----------------------------------------------------------------------===// /// Print coverage information to output stream {@code o}. /// May modify the used list of files {@code Fids} by inserting new ones. static void printCoverage(const PathDiagnostic *D, unsigned InputIndentLevel, SmallVectorImpl &Fids, FIDMap &FM, llvm::raw_fd_ostream &o) { unsigned IndentLevel = InputIndentLevel; Indent(o, IndentLevel) << "ExecutedLines\n"; Indent(o, IndentLevel) << "\n"; IndentLevel++; // Mapping from file IDs to executed lines. const FilesToLineNumsMap &ExecutedLines = D->getExecutedLines(); for (auto I = ExecutedLines.begin(), E = ExecutedLines.end(); I != E; ++I) { unsigned FileKey = AddFID(FM, Fids, I->first); Indent(o, IndentLevel) << "" << FileKey << "\n"; Indent(o, IndentLevel) << "\n"; IndentLevel++; for (unsigned LineNo : I->second) { Indent(o, IndentLevel); EmitInteger(o, LineNo) << "\n"; } IndentLevel--; Indent(o, IndentLevel) << "\n"; } IndentLevel--; Indent(o, IndentLevel) << "\n"; assert(IndentLevel == InputIndentLevel); } static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM, AnalyzerOptions &AnOpts, const Preprocessor &PP, const PathPieces &Path) { PlistPrinter Printer(FM, AnOpts, PP); assert(std::is_partitioned( Path.begin(), Path.end(), [](const std::shared_ptr &E) { return E->getKind() == PathDiagnosticPiece::Note; }) && "PathDiagnostic is not partitioned so that notes precede the rest"); PathPieces::const_iterator FirstNonNote = std::partition_point( Path.begin(), Path.end(), [](const std::shared_ptr &E) { return E->getKind() == PathDiagnosticPiece::Note; }); PathPieces::const_iterator I = Path.begin(); if (FirstNonNote != Path.begin()) { o << " notes\n" " \n"; for (; I != FirstNonNote; ++I) Printer.ReportDiag(o, **I); o << " \n"; } o << " path\n"; o << " \n"; for (PathPieces::const_iterator E = Path.end(); I != E; ++I) Printer.ReportDiag(o, **I); o << " \n"; if (!AnOpts.shouldDisplayMacroExpansions()) return; o << " macro_expansions\n" " \n"; Printer.ReportMacroExpansions(o, /* indent */ 4); o << " \n"; } //===----------------------------------------------------------------------===// // Methods of PlistDiagnostics. //===----------------------------------------------------------------------===// PlistDiagnostics::PlistDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string& output, const Preprocessor &PP, bool supportsMultipleFiles) : OutputFile(output), PP(PP), AnOpts(AnalyzerOpts), SupportsCrossFileDiagnostics(supportsMultipleFiles) {} void ento::createPlistDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C, const std::string& s, const Preprocessor &PP) { C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, /*supportsMultipleFiles*/ false)); } void ento::createPlistMultiFileDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C, const std::string &s, const Preprocessor &PP) { C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, /*supportsMultipleFiles*/ true)); } void PlistDiagnostics::FlushDiagnosticsImpl( std::vector &Diags, FilesMade *filesMade) { // Build up a set of FIDs that we use by scanning the locations and // ranges of the diagnostics. FIDMap FM; SmallVector Fids; const SourceManager& SM = PP.getSourceManager(); const LangOptions &LangOpts = PP.getLangOpts(); auto AddPieceFID = [&FM, &Fids, &SM](const PathDiagnosticPiece &Piece) { AddFID(FM, Fids, SM, Piece.getLocation().asLocation()); ArrayRef Ranges = Piece.getRanges(); for (const SourceRange &Range : Ranges) { AddFID(FM, Fids, SM, Range.getBegin()); AddFID(FM, Fids, SM, Range.getEnd()); } }; for (const PathDiagnostic *D : Diags) { SmallVector WorkList; WorkList.push_back(&D->path); while (!WorkList.empty()) { const PathPieces &Path = *WorkList.pop_back_val(); for (const auto &Iter : Path) { const PathDiagnosticPiece &Piece = *Iter; AddPieceFID(Piece); if (const PathDiagnosticCallPiece *Call = dyn_cast(&Piece)) { if (auto CallEnterWithin = Call->getCallEnterWithinCallerEvent()) AddPieceFID(*CallEnterWithin); if (auto CallEnterEvent = Call->getCallEnterEvent()) AddPieceFID(*CallEnterEvent); WorkList.push_back(&Call->path); } else if (const PathDiagnosticMacroPiece *Macro = dyn_cast(&Piece)) { WorkList.push_back(&Macro->subPieces); } } } } // Open the file. std::error_code EC; llvm::raw_fd_ostream o(OutputFile, EC, llvm::sys::fs::F_Text); if (EC) { llvm::errs() << "warning: could not create file: " << EC.message() << '\n'; return; } EmitPlistHeader(o); // Write the root object: a containing... // - "clang_version", the string representation of clang version // - "files", an mapping from FIDs to file names // - "diagnostics", an containing the path diagnostics o << "\n" << " clang_version\n"; EmitString(o, getClangFullVersion()) << '\n'; o << " diagnostics\n" " \n"; for (std::vector::iterator DI=Diags.begin(), DE = Diags.end(); DI!=DE; ++DI) { o << " \n"; const PathDiagnostic *D = *DI; printBugPath(o, FM, AnOpts, PP, D->path); // Output the bug type and bug category. o << " description"; EmitString(o, D->getShortDescription()) << '\n'; o << " category"; EmitString(o, D->getCategory()) << '\n'; o << " type"; EmitString(o, D->getBugType()) << '\n'; o << " check_name"; EmitString(o, D->getCheckName()) << '\n'; o << " \n"; o << " issue_hash_content_of_line_in_context"; PathDiagnosticLocation UPDLoc = D->getUniqueingLoc(); FullSourceLoc L(SM.getExpansionLoc(UPDLoc.isValid() ? UPDLoc.asLocation() : D->getLocation().asLocation()), SM); const Decl *DeclWithIssue = D->getDeclWithIssue(); EmitString(o, GetIssueHash(SM, L, D->getCheckName(), D->getBugType(), DeclWithIssue, LangOpts)) << '\n'; // Output information about the semantic context where // the issue occurred. if (const Decl *DeclWithIssue = D->getDeclWithIssue()) { // FIXME: handle blocks, which have no name. if (const NamedDecl *ND = dyn_cast(DeclWithIssue)) { StringRef declKind; switch (ND->getKind()) { case Decl::CXXRecord: declKind = "C++ class"; break; case Decl::CXXMethod: declKind = "C++ method"; break; case Decl::ObjCMethod: declKind = "Objective-C method"; break; case Decl::Function: declKind = "function"; break; default: break; } if (!declKind.empty()) { const std::string &declName = ND->getDeclName().getAsString(); o << " issue_context_kind"; EmitString(o, declKind) << '\n'; o << " issue_context"; EmitString(o, declName) << '\n'; } // Output the bug hash for issue unique-ing. Currently, it's just an // offset from the beginning of the function. if (const Stmt *Body = DeclWithIssue->getBody()) { // If the bug uniqueing location exists, use it for the hash. // For example, this ensures that two leaks reported on the same line // will have different issue_hashes and that the hash will identify // the leak location even after code is added between the allocation // site and the end of scope (leak report location). if (UPDLoc.isValid()) { FullSourceLoc UFunL( SM.getExpansionLoc( D->getUniqueingDecl()->getBody()->getBeginLoc()), SM); o << " issue_hash_function_offset" << L.getExpansionLineNumber() - UFunL.getExpansionLineNumber() << "\n"; // Otherwise, use the location on which the bug is reported. } else { FullSourceLoc FunL(SM.getExpansionLoc(Body->getBeginLoc()), SM); o << " issue_hash_function_offset" << L.getExpansionLineNumber() - FunL.getExpansionLineNumber() << "\n"; } } } } // Output the location of the bug. o << " location\n"; EmitLocation(o, SM, D->getLocation().asLocation(), FM, 2); // Output the diagnostic to the sub-diagnostic client, if any. if (!filesMade->empty()) { StringRef lastName; PDFileEntry::ConsumerFiles *files = filesMade->getFiles(*D); if (files) { for (PDFileEntry::ConsumerFiles::const_iterator CI = files->begin(), CE = files->end(); CI != CE; ++CI) { StringRef newName = CI->first; if (newName != lastName) { if (!lastName.empty()) { o << " \n"; } lastName = newName; o << " " << lastName << "_files\n"; o << " \n"; } o << " " << CI->second << "\n"; } o << " \n"; } } printCoverage(D, /*IndentLevel=*/2, Fids, FM, o); // Close up the entry. o << " \n"; } o << " \n"; o << " files\n" " \n"; for (FileID FID : Fids) EmitString(o << " ", SM.getFileEntryForID(FID)->getName()) << '\n'; o << " \n"; if (llvm::AreStatisticsEnabled() && AnOpts.shouldSerializeStats()) { o << " statistics\n"; std::string stats; llvm::raw_string_ostream os(stats); llvm::PrintStatisticsJSON(os); os.flush(); EmitString(o, html::EscapeText(stats)) << '\n'; } // Finish. o << "\n"; } //===----------------------------------------------------------------------===// // Declarations of helper functions and data structures for expanding macros. //===----------------------------------------------------------------------===// namespace { struct MacroNameAndInfo { std::string Name; const MacroInfo *MI = nullptr; MacroNameAndInfo(std::string N, const MacroInfo *MI) : Name(std::move(N)), MI(MI) {} }; /// Helper class for printing tokens. class TokenPrinter { llvm::raw_ostream &OS; const Preprocessor &PP; Token PrevTok, PrevPrevTok; TokenConcatenation ConcatInfo; public: TokenPrinter(llvm::raw_ostream &OS, const Preprocessor &PP) : OS(OS), PP(PP), ConcatInfo(PP) { PrevTok.setKind(tok::unknown); PrevPrevTok.setKind(tok::unknown); } void printToken(const Token &Tok); }; } // end of anonymous namespace static std::string getMacroNameAndPrintExpansion(TokenPrinter &Printer, SourceLocation MacroLoc, const Preprocessor &PP); /// Retrieves the name of the macro and its MacroInfo. static MacroNameAndInfo getMacroNameAndInfo(SourceLocation ExpanLoc, const Preprocessor &PP); /// Retrieves the ')' token that matches '(' \p It points to. static MacroInfo::tokens_iterator getMatchingRParen( MacroInfo::tokens_iterator It, MacroInfo::tokens_iterator End); /// Retrieves the macro info for \p II refers to at \p Loc. This is important /// because macros can be redefined or undefined. static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP, const SourceManager &SM, const IdentifierInfo *II, SourceLocation Loc); //===----------------------------------------------------------------------===// // Definitions of helper functions and methods for expanding macros. //===----------------------------------------------------------------------===// static ExpansionInfo getExpandedMacro(SourceLocation MacroLoc, const Preprocessor &PP) { llvm::SmallString<200> ExpansionBuf; llvm::raw_svector_ostream OS(ExpansionBuf); TokenPrinter Printer(OS, PP); std::string MacroName = getMacroNameAndPrintExpansion(Printer, MacroLoc, PP); return { MacroName, OS.str() }; } static std::string getMacroNameAndPrintExpansion(TokenPrinter &Printer, SourceLocation MacroLoc, const Preprocessor &PP) { const SourceManager &SM = PP.getSourceManager(); MacroNameAndInfo Info = getMacroNameAndInfo(SM.getExpansionLoc(MacroLoc), PP); const MacroInfo *MI = Info.MI; // Iterate over the macro's tokens and stringify them. for (auto It = MI->tokens_begin(), E = MI->tokens_end(); It != E; ++It) { Token T = *It; // If this token is not an identifier, we only need to print it. if (T.isNot(tok::identifier)) { Printer.printToken(T); continue; } const auto *II = T.getIdentifierInfo(); assert(II && "This token is an identifier but has no IdentifierInfo!"); // If this token is a macro that should be expanded inside the currect // macro. if (const MacroInfo *MI = getMacroInfoForLocation(PP, SM, II, T.getLocation())) { getMacroNameAndPrintExpansion(Printer, T.getLocation(), PP); // If this is a function-like macro, skip its arguments, as // getExpandedMacro() already printed them. If this is the case, let's // first jumo to the '(' token. if (MI->getNumParams() != 0) It = getMatchingRParen(++It, E); continue; } // If control reached here, then this token isn't a macro identifier, print // it. Printer.printToken(T); } return Info.Name; } static MacroNameAndInfo getMacroNameAndInfo(SourceLocation ExpanLoc, const Preprocessor &PP) { const SourceManager &SM = PP.getSourceManager(); const LangOptions &LangOpts = PP.getLangOpts(); // First, we create a Lexer to lex *at the expansion location* the tokens // referring to the macro's name and its arguments. std::pair LocInfo = SM.getDecomposedLoc(ExpanLoc); const llvm::MemoryBuffer *MB = SM.getBuffer(LocInfo.first); const char *MacroNameTokenPos = MB->getBufferStart() + LocInfo.second; Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, MB->getBufferStart(), MacroNameTokenPos, MB->getBufferEnd()); // Acquire the macro's name. Token TheTok; RawLexer.LexFromRawLexer(TheTok); std::string MacroName = PP.getSpelling(TheTok); const auto *II = PP.getIdentifierInfo(MacroName); assert(II && "Failed to acquire the IndetifierInfo for the macro!"); const MacroInfo *MI = getMacroInfoForLocation(PP, SM, II, ExpanLoc); assert(MI && "The macro must've been defined at it's expansion location!"); return { MacroName, MI }; } static MacroInfo::tokens_iterator getMatchingRParen( MacroInfo::tokens_iterator It, MacroInfo::tokens_iterator End) { assert(It->is(tok::l_paren) && "This token should be '('!"); // Skip until we find the closing ')'. int ParanthesesDepth = 1; while (ParanthesesDepth != 0) { ++It; assert(It->isNot(tok::eof) && "Encountered EOF while attempting to skip macro arguments!"); assert(It != End && "End of the macro definition reached before finding ')'!"); if (It->is(tok::l_paren)) ++ParanthesesDepth; if (It->is(tok::r_paren)) --ParanthesesDepth; } return It; } static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP, const SourceManager &SM, const IdentifierInfo *II, SourceLocation Loc) { const MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II); if (!MD) return nullptr; return MD->findDirectiveAtLoc(Loc, SM).getMacroInfo(); } void TokenPrinter::printToken(const Token &Tok) { // If the tokens were already space separated, or if they must be to avoid // them being implicitly pasted, add a space between them. // If this is the first token to be printed, don't print space. if (PrevTok.isNot(tok::unknown) && (Tok.hasLeadingSpace() || ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok))) OS << ' '; OS << PP.getSpelling(Tok); PrevPrevTok = PrevTok; PrevTok = Tok; }