#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <set>
using namespace clang;
namespace {
class InheritanceHierarchyWriter {
ASTContext& Context;
raw_ostream &Out;
std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
std::set<QualType, QualTypeOrdering> KnownVirtualBases;
public:
InheritanceHierarchyWriter(ASTContext& Context, raw_ostream& Out)
: Context(Context), Out(Out) { }
void WriteGraph(QualType Type) {
Out << "digraph \"" << llvm::DOT::EscapeString(Type.getAsString())
<< "\" {\n";
WriteNode(Type, false);
Out << "}\n";
}
protected:
void WriteNode(QualType Type, bool FromVirtual);
raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};
}
void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
if (FromVirtual) {
if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
return;
KnownVirtualBases.insert(CanonType);
}
Out << " ";
WriteNodeReference(Type, FromVirtual);
std::string TypeName = Type.getAsString();
Out << " [ shape=\"box\", label=\"" << llvm::DOT::EscapeString(TypeName);
if (TypeName != CanonType.getAsString()) {
Out << "\\n(" << CanonType.getAsString() << ")";
}
Out << " \"];\n";
const CXXRecordDecl *Decl
= static_cast<const CXXRecordDecl *>(Type->getAs<RecordType>()->getDecl());
for (const auto &Base : Decl->bases()) {
QualType CanonBaseType = Context.getCanonicalType(Base.getType());
if (!Base.isVirtual())
++DirectBaseCount[CanonBaseType];
WriteNode(Base.getType(), Base.isVirtual());
Out << " ";
WriteNodeReference(Type, FromVirtual);
Out << " -> ";
WriteNodeReference(Base.getType(), Base.isVirtual());
if (Base.isVirtual()) {
Out << " [ style=\"dashed\" ]";
}
Out << ";";
}
}
raw_ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
bool FromVirtual) {
QualType CanonType = Context.getCanonicalType(Type);
Out << "Class_" << CanonType.getAsOpaquePtr();
if (!FromVirtual)
Out << "_" << DirectBaseCount[CanonType];
return Out;
}
void CXXRecordDecl::viewInheritance(ASTContext& Context) const {
QualType Self = Context.getTypeDeclType(this);
int FD;
SmallString<128> Filename;
if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
Self.getAsString(), "dot", FD, Filename)) {
llvm::errs() << "Error: " << EC.message() << "\n";
return;
}
llvm::errs() << "Writing '" << Filename << "'... ";
llvm::raw_fd_ostream O(FD, true);
InheritanceHierarchyWriter Writer(Context, O);
Writer.WriteGraph(Self);
llvm::errs() << " done. \n";
O.close();
DisplayGraph(Filename);
}