#include "clang/Frontend/DiagnosticRenderer.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Edit/EditsReceiver.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <utility>
using namespace clang;
DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
DiagnosticOptions *DiagOpts)
: LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
DiagnosticRenderer::~DiagnosticRenderer() = default;
namespace {
class FixitReceiver : public edit::EditsReceiver {
SmallVectorImpl<FixItHint> &MergedFixits;
public:
FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
: MergedFixits(MergedFixits) {}
void insert(SourceLocation loc, StringRef text) override {
MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
}
void replace(CharSourceRange range, StringRef text) override {
MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
}
};
}
static void mergeFixits(ArrayRef<FixItHint> FixItHints,
const SourceManager &SM, const LangOptions &LangOpts,
SmallVectorImpl<FixItHint> &MergedFixits) {
edit::Commit commit(SM, LangOpts);
for (const auto &Hint : FixItHints)
if (Hint.CodeToInsert.empty()) {
if (Hint.InsertFromRange.isValid())
commit.insertFromRange(Hint.RemoveRange.getBegin(),
Hint.InsertFromRange, false,
Hint.BeforePreviousInsertions);
else
commit.remove(Hint.RemoveRange);
} else {
if (Hint.RemoveRange.isTokenRange() ||
Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
else
commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
false, Hint.BeforePreviousInsertions);
}
edit::EditedSource Editor(SM, LangOpts);
if (Editor.commit(commit)) {
FixitReceiver Rec(MergedFixits);
Editor.applyRewrites(Rec);
}
}
void DiagnosticRenderer::emitDiagnostic(FullSourceLoc Loc,
DiagnosticsEngine::Level Level,
StringRef Message,
ArrayRef<CharSourceRange> Ranges,
ArrayRef<FixItHint> FixItHints,
DiagOrStoredDiag D) {
assert(Loc.hasManager() || Loc.isInvalid());
beginDiagnostic(D, Level);
if (!Loc.isValid())
emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, D);
else {
SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
Ranges.end());
SmallVector<FixItHint, 8> MergedFixits;
if (!FixItHints.empty()) {
mergeFixits(FixItHints, Loc.getManager(), LangOpts, MergedFixits);
FixItHints = MergedFixits;
}
for (const auto &Hint : FixItHints)
if (Hint.RemoveRange.isValid())
MutableRanges.push_back(Hint.RemoveRange);
FullSourceLoc UnexpandedLoc = Loc;
Loc = Loc.getFileLoc();
PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
emitIncludeStack(Loc, PLoc, Level);
emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
emitCaret(Loc, Level, MutableRanges, FixItHints);
if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints);
}
}
LastLoc = Loc;
LastLevel = Level;
endDiagnostic(D, Level);
}
void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
Diag.getRanges(), Diag.getFixIts(),
&Diag);
}
void DiagnosticRenderer::emitBasicNote(StringRef Message) {
emitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagnosticsEngine::Note,
Message, None, DiagOrStoredDiag());
}
void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc,
DiagnosticsEngine::Level Level) {
FullSourceLoc IncludeLoc =
PLoc.isInvalid() ? FullSourceLoc()
: FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
if (LastIncludeLoc == IncludeLoc)
return;
LastIncludeLoc = IncludeLoc;
if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
return;
if (IncludeLoc.isValid())
emitIncludeStackRecursively(IncludeLoc);
else {
emitModuleBuildStack(Loc.getManager());
emitImportStack(Loc);
}
}
void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) {
if (Loc.isInvalid()) {
emitModuleBuildStack(Loc.getManager());
return;
}
PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
if (PLoc.isInvalid())
return;
std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc();
if (!Imported.second.empty()) {
emitImportStackRecursively(Imported.first, Imported.second);
return;
}
emitIncludeStackRecursively(
FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager()));
emitIncludeLocation(Loc, PLoc);
}
void DiagnosticRenderer::emitImportStack(FullSourceLoc Loc) {
if (Loc.isInvalid()) {
emitModuleBuildStack(Loc.getManager());
return;
}
std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
}
void DiagnosticRenderer::emitImportStackRecursively(FullSourceLoc Loc,
StringRef ModuleName) {
if (ModuleName.empty()) {
return;
}
PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
emitImportLocation(Loc, PLoc, ModuleName);
}
void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
ModuleBuildStack Stack = SM.getModuleBuildStack();
for (const auto &I : Stack) {
emitBuildingModuleLocation(I.second, I.second.getPresumedLoc(
DiagOpts->ShowPresumedLoc),
I.first);
}
}
static SourceLocation
retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
FileID CaretFileID,
const SmallVectorImpl<FileID> &CommonArgExpansions,
bool IsBegin, const SourceManager *SM,
bool &IsTokenRange) {
assert(SM->getFileID(Loc) == MacroFileID);
if (MacroFileID == CaretFileID)
return Loc;
if (!Loc.isMacroID())
return {};
CharSourceRange MacroRange, MacroArgRange;
if (SM->isMacroArgExpansion(Loc)) {
if (std::binary_search(CommonArgExpansions.begin(),
CommonArgExpansions.end(), MacroFileID))
MacroRange =
CharSourceRange(SM->getImmediateSpellingLoc(Loc), IsTokenRange);
MacroArgRange = SM->getImmediateExpansionRange(Loc);
} else {
MacroRange = SM->getImmediateExpansionRange(Loc);
MacroArgRange =
CharSourceRange(SM->getImmediateSpellingLoc(Loc), IsTokenRange);
}
SourceLocation MacroLocation =
IsBegin ? MacroRange.getBegin() : MacroRange.getEnd();
if (MacroLocation.isValid()) {
MacroFileID = SM->getFileID(MacroLocation);
bool TokenRange = IsBegin ? IsTokenRange : MacroRange.isTokenRange();
MacroLocation =
retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
CommonArgExpansions, IsBegin, SM, TokenRange);
if (MacroLocation.isValid()) {
IsTokenRange = TokenRange;
return MacroLocation;
}
}
if (!IsBegin)
IsTokenRange = MacroArgRange.isTokenRange();
SourceLocation MacroArgLocation =
IsBegin ? MacroArgRange.getBegin() : MacroArgRange.getEnd();
MacroFileID = SM->getFileID(MacroArgLocation);
return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
CommonArgExpansions, IsBegin, SM, IsTokenRange);
}
static void getMacroArgExpansionFileIDs(SourceLocation Loc,
SmallVectorImpl<FileID> &IDs,
bool IsBegin, const SourceManager *SM) {
while (Loc.isMacroID()) {
if (SM->isMacroArgExpansion(Loc)) {
IDs.push_back(SM->getFileID(Loc));
Loc = SM->getImmediateSpellingLoc(Loc);
} else {
auto ExpRange = SM->getImmediateExpansionRange(Loc);
Loc = IsBegin ? ExpRange.getBegin() : ExpRange.getEnd();
}
}
}
static void computeCommonMacroArgExpansionFileIDs(
SourceLocation Begin, SourceLocation End, const SourceManager *SM,
SmallVectorImpl<FileID> &CommonArgExpansions) {
SmallVector<FileID, 4> BeginArgExpansions;
SmallVector<FileID, 4> EndArgExpansions;
getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, true, SM);
getMacroArgExpansionFileIDs(End, EndArgExpansions, false, SM);
llvm::sort(BeginArgExpansions);
llvm::sort(EndArgExpansions);
std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
EndArgExpansions.begin(), EndArgExpansions.end(),
std::back_inserter(CommonArgExpansions));
}
static void
mapDiagnosticRanges(FullSourceLoc CaretLoc, ArrayRef<CharSourceRange> Ranges,
SmallVectorImpl<CharSourceRange> &SpellingRanges) {
FileID CaretLocFileID = CaretLoc.getFileID();
const SourceManager *SM = &CaretLoc.getManager();
for (const auto &Range : Ranges) {
if (Range.isInvalid())
continue;
SourceLocation Begin = Range.getBegin(), End = Range.getEnd();
bool IsTokenRange = Range.isTokenRange();
FileID BeginFileID = SM->getFileID(Begin);
FileID EndFileID = SM->getFileID(End);
llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
while (Begin.isMacroID() && BeginFileID != EndFileID) {
BeginLocsMap[BeginFileID] = Begin;
Begin = SM->getImmediateExpansionRange(Begin).getBegin();
BeginFileID = SM->getFileID(Begin);
}
if (BeginFileID != EndFileID) {
while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
auto Exp = SM->getImmediateExpansionRange(End);
IsTokenRange = Exp.isTokenRange();
End = Exp.getEnd();
EndFileID = SM->getFileID(End);
}
if (End.isMacroID()) {
Begin = BeginLocsMap[EndFileID];
BeginFileID = EndFileID;
}
}
if (Begin.isInvalid() || End.isInvalid() || BeginFileID != EndFileID)
continue;
SmallVector<FileID, 4> CommonArgExpansions;
computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
CommonArgExpansions, true, SM,
IsTokenRange);
End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
CommonArgExpansions, false, SM,
IsTokenRange);
if (Begin.isInvalid() || End.isInvalid()) continue;
Begin = SM->getSpellingLoc(Begin);
End = SM->getSpellingLoc(End);
SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
IsTokenRange));
}
}
void DiagnosticRenderer::emitCaret(FullSourceLoc Loc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
ArrayRef<FixItHint> Hints) {
SmallVector<CharSourceRange, 4> SpellingRanges;
mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
emitCodeContext(Loc, Level, SpellingRanges, Hints);
}
void DiagnosticRenderer::emitSingleMacroExpansion(
FullSourceLoc Loc, DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges) {
FullSourceLoc SpellingLoc = Loc.getSpellingLoc();
SmallVector<CharSourceRange, 4> SpellingRanges;
mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
SmallString<100> MessageStorage;
llvm::raw_svector_ostream Message(MessageStorage);
StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
Loc, Loc.getManager(), LangOpts);
if (MacroName.empty())
Message << "expanded from here";
else
Message << "expanded from macro '" << MacroName << "'";
emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
SpellingRanges, None);
}
static bool checkLocForMacroArgExpansion(SourceLocation Loc,
const SourceManager &SM,
SourceLocation ArgumentLoc) {
SourceLocation MacroLoc;
if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
if (ArgumentLoc == MacroLoc) return true;
}
return false;
}
static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
const SourceManager &SM,
SourceLocation ArgumentLoc) {
SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
while (BegLoc != EndLoc) {
if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
return false;
BegLoc.getLocWithOffset(1);
}
return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
}
static bool checkRangesForMacroArgExpansion(FullSourceLoc Loc,
ArrayRef<CharSourceRange> Ranges) {
assert(Loc.isMacroID() && "Must be a macro expansion!");
SmallVector<CharSourceRange, 4> SpellingRanges;
mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
unsigned ValidCount = 0;
for (const auto &Range : Ranges)
if (Range.isValid())
ValidCount++;
if (ValidCount > SpellingRanges.size())
return false;
FullSourceLoc ArgumentLoc;
if (!Loc.isMacroArgExpansion(&ArgumentLoc))
return false;
for (const auto &Range : SpellingRanges)
if (!checkRangeForMacroArgExpansion(Range, Loc.getManager(), ArgumentLoc))
return false;
return true;
}
void DiagnosticRenderer::emitMacroExpansions(FullSourceLoc Loc,
DiagnosticsEngine::Level Level,
ArrayRef<CharSourceRange> Ranges,
ArrayRef<FixItHint> Hints) {
assert(Loc.isValid() && "must have a valid source location here");
const SourceManager &SM = Loc.getManager();
SourceLocation L = Loc;
SmallVector<SourceLocation, 8> LocationStack;
unsigned IgnoredEnd = 0;
while (L.isMacroID()) {
if (SM.isMacroArgExpansion(L))
LocationStack.push_back(SM.getImmediateExpansionRange(L).getBegin());
else
LocationStack.push_back(L);
if (checkRangesForMacroArgExpansion(FullSourceLoc(L, SM), Ranges))
IgnoredEnd = LocationStack.size();
L = SM.getImmediateMacroCallerLoc(L);
if (L.isFileID())
L = SM.getImmediateMacroCallerLoc(LocationStack.back());
assert(L.isValid() && "must have a valid source location here");
}
LocationStack.erase(LocationStack.begin(),
LocationStack.begin() + IgnoredEnd);
unsigned MacroDepth = LocationStack.size();
unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
if (MacroDepth <= MacroLimit || MacroLimit == 0) {
for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
I != E; ++I)
emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
return;
}
unsigned MacroStartMessages = MacroLimit / 2;
unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
for (auto I = LocationStack.rbegin(),
E = LocationStack.rbegin() + MacroStartMessages;
I != E; ++I)
emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
SmallString<200> MessageStorage;
llvm::raw_svector_ostream Message(MessageStorage);
Message << "(skipping " << (MacroDepth - MacroLimit)
<< " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
"see all)";
emitBasicNote(Message.str());
for (auto I = LocationStack.rend() - MacroEndMessages,
E = LocationStack.rend();
I != E; ++I)
emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
}
DiagnosticNoteRenderer::~DiagnosticNoteRenderer() = default;
void DiagnosticNoteRenderer::emitIncludeLocation(FullSourceLoc Loc,
PresumedLoc PLoc) {
SmallString<200> MessageStorage;
llvm::raw_svector_ostream Message(MessageStorage);
Message << "in file included from " << PLoc.getFilename() << ':'
<< PLoc.getLine() << ":";
emitNote(Loc, Message.str());
}
void DiagnosticNoteRenderer::emitImportLocation(FullSourceLoc Loc,
PresumedLoc PLoc,
StringRef ModuleName) {
SmallString<200> MessageStorage;
llvm::raw_svector_ostream Message(MessageStorage);
Message << "in module '" << ModuleName;
if (PLoc.isValid())
Message << "' imported from " << PLoc.getFilename() << ':'
<< PLoc.getLine();
Message << ":";
emitNote(Loc, Message.str());
}
void DiagnosticNoteRenderer::emitBuildingModuleLocation(FullSourceLoc Loc,
PresumedLoc PLoc,
StringRef ModuleName) {
SmallString<200> MessageStorage;
llvm::raw_svector_ostream Message(MessageStorage);
if (PLoc.isValid())
Message << "while building module '" << ModuleName << "' imported from "
<< PLoc.getFilename() << ':' << PLoc.getLine() << ":";
else
Message << "while building module '" << ModuleName << "':";
emitNote(Loc, Message.str());
}