Commit 23decd9d authored by Leandro Melo's avatar Leandro Melo Committed by Leandro T. C. Melo

C++ editor: Improve type hierarchy widget

Now the type hierarchy widget will also show the classes
derived from the selected one. For consistency the way
the base classes are shown was changed too. The diagram
below is an example from Creator's code when openining
the type hierarchy for BaseTextEditorWidget:

Bases
 +QObject
  +QWidget
   +...
     BaseTextEditorWidget
 +QPaintDevice
  +...
    BaseTextEditorWidget
Derived
 +BaseTextEditorWidget
  +VCSBaseEditorWidget
    GitEditor
    MercurialEditor
    ...
   GLSLEditorWidget
   CppEditorWidget
   QmlJSTextEditorWidget
   ...

Depending on the project and on the selected class the
hierarchy widget might take a bit to be constructed.
This should be improved later.

Change-Id: Ifbdd1cbbba955a0bdf03297ff0e7620351b12dc5
Reviewed-on: http://codereview.qt.nokia.com/883Reviewed-by: default avatarRoberto Raggi <roberto.raggi@nokia.com>
parent b260bf1e
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "TypeHierarchyBuilder.h"
#include "FindUsages.h"
#include "Symbols.h"
#include "SymbolVisitor.h"
#include "DependencyTable.h"
#include "CppDocument.h"
#include "Literals.h"
#include "TranslationUnit.h"
#include "CoreTypes.h"
using namespace CPlusPlus;
namespace {
QString unqualifyName(const QString &qualifiedName)
{
const int index = qualifiedName.lastIndexOf(QLatin1String("::"));
if (index == -1)
return qualifiedName;
return qualifiedName.right(qualifiedName.length() - index - 2);
}
class DerivedHierarchyVisitor : public SymbolVisitor
{
public:
DerivedHierarchyVisitor(const QString &qualifiedName)
: _qualifiedName(qualifiedName)
, _unqualifiedName(unqualifyName(qualifiedName))
{}
void execute(const Document::Ptr &doc, const Snapshot &snapshot);
virtual bool visit(Class *);
const QList<Symbol *> &derived() { return _derived; }
const QStringList otherBases() { return _otherBases; }
private:
LookupContext _context;
QString _qualifiedName;
QString _unqualifiedName;
Overview _overview;
QHash<Symbol *, QString> _actualBases;
QStringList _otherBases;
QList<Symbol *> _derived;
};
void DerivedHierarchyVisitor::execute(const Document::Ptr &doc, const Snapshot &snapshot)
{
_derived.clear();
_otherBases.clear();
_context = LookupContext(doc, snapshot);
for (unsigned i = 0; i < doc->globalSymbolCount(); ++i)
accept(doc->globalSymbolAt(i));
}
bool DerivedHierarchyVisitor::visit(Class *symbol)
{
for (unsigned i = 0; i < symbol->baseClassCount(); ++i) {
BaseClass *baseSymbol = symbol->baseClassAt(i);
QString baseName = _actualBases.value(baseSymbol);
if (baseName.isEmpty()) {
QList<LookupItem> items = _context.lookup(baseSymbol->name(), symbol->enclosingScope());
if (items.isEmpty() || !items.first().declaration())
continue;
Symbol *actualBaseSymbol = items.first().declaration();
if (actualBaseSymbol->isTypedef()) {
NamedType *namedType = actualBaseSymbol->type()->asNamedType();
const QString &typeName = _overview.prettyName(namedType->name());
if (namedType &&
(typeName == _unqualifiedName || typeName == _qualifiedName)) {
items = _context.lookup(namedType->name(), actualBaseSymbol->enclosingScope());
if (items.isEmpty() || !items.first().declaration())
continue;
actualBaseSymbol = items.first().declaration();
}
}
const QList<const Name *> &full = LookupContext::fullyQualifiedName(actualBaseSymbol);
baseName = _overview.prettyName(full);
_actualBases.insert(baseSymbol, baseName);
}
if (_qualifiedName == baseName)
_derived.append(symbol);
else
_otherBases.append(baseName);
}
return true;
}
}
TypeHierarchy::TypeHierarchy() : _symbol(0)
{}
TypeHierarchy::TypeHierarchy(Symbol *symbol) : _symbol(symbol)
{}
Symbol *TypeHierarchy::symbol() const
{
return _symbol;
}
const QList<TypeHierarchy> &TypeHierarchy::hierarchy() const
{
return _hierarchy;
}
TypeHierarchyBuilder::TypeHierarchyBuilder(Symbol *symbol, const Snapshot &snapshot)
: _symbol(symbol)
, _snapshot(snapshot)
, _dependencies(QString::fromUtf8(symbol->fileName(), symbol->fileNameLength()))
{
DependencyTable dependencyTable;
dependencyTable.build(_snapshot);
_dependencies.append(dependencyTable.filesDependingOn(_dependencies.first()));
}
void TypeHierarchyBuilder::reset()
{
_visited.clear();
_candidates.clear();
}
TypeHierarchy TypeHierarchyBuilder::buildDerivedTypeHierarchy()
{
reset();
TypeHierarchy hierarchy(_symbol);
buildDerived(&hierarchy);
return hierarchy;
}
void TypeHierarchyBuilder::buildDerived(TypeHierarchy *typeHierarchy)
{
Symbol *symbol = typeHierarchy->_symbol;
if (_visited.contains(symbol))
return;
_visited.insert(symbol);
const QString &symbolName = _overview.prettyName(LookupContext::fullyQualifiedName(symbol));
DerivedHierarchyVisitor visitor(symbolName);
foreach (const QString &fileName, _dependencies) {
Document::Ptr doc = _snapshot.document(fileName);
if ((_candidates.contains(fileName) && !_candidates.value(fileName).contains(symbolName))
|| !doc->control()->findIdentifier(symbol->identifier()->chars(),
symbol->identifier()->size())) {
continue;
}
visitor.execute(doc, _snapshot);
_candidates.insert(fileName, QSet<QString>());
foreach (const QString &candidate, visitor.otherBases())
_candidates[fileName].insert(candidate);
foreach (Symbol *s, visitor.derived()) {
TypeHierarchy derivedHierarchy(s);
buildDerived(&derivedHierarchy);
typeHierarchy->_hierarchy.append(derivedHierarchy);
}
}
}
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#ifndef FINDDERIVEDCLASSES_H
#define FINDDERIVEDCLASSES_H
#include "CppDocument.h"
#include "ModelManagerInterface.h"
#include "Overview.h"
#include <QtCore/QList>
#include <QtCore/QStringList>
#include <QtCore/QSet>
namespace CPlusPlus {
class CPLUSPLUS_EXPORT TypeHierarchy
{
friend class TypeHierarchyBuilder;
public:
TypeHierarchy();
TypeHierarchy(Symbol *symbol);
Symbol *symbol() const;
const QList<TypeHierarchy> &hierarchy() const;
private:
Symbol *_symbol;
QList<TypeHierarchy> _hierarchy;
};
class CPLUSPLUS_EXPORT TypeHierarchyBuilder
{
public:
TypeHierarchyBuilder(Symbol *symbol, const Snapshot &snapshot);
TypeHierarchy buildDerivedTypeHierarchy();
private:
void reset();
void buildDerived(TypeHierarchy *typeHierarchy);
Symbol *_symbol;
Snapshot _snapshot;
QStringList _dependencies;
QSet<Symbol *> _visited;
QHash<QString, QSet<QString> > _candidates;
Overview _overview;
};
} // CPlusPlus
#endif // FINDDERIVEDCLASSES_H
......@@ -52,7 +52,8 @@ HEADERS += \
$$PWD/pp-macro-expander.h \
$$PWD/pp-scanner.h \
$$PWD/ModelManagerInterface.h \
$$PWD/findcdbbreakpoint.h
$$PWD/findcdbbreakpoint.h \
$$PWD/TypeHierarchyBuilder.h
SOURCES += \
$$PWD/SimpleLexer.cpp \
......@@ -80,10 +81,7 @@ SOURCES += \
$$PWD/pp-macro-expander.cpp \
$$PWD/pp-scanner.cpp \
$$PWD/ModelManagerInterface.cpp \
$$PWD/findcdbbreakpoint.cpp
$$PWD/findcdbbreakpoint.cpp \
$$PWD/TypeHierarchyBuilder.cpp
RESOURCES += $$PWD/cplusplus.qrc
......@@ -33,6 +33,7 @@
#include "cppelementevaluator.h"
#include <coreplugin/ifile.h>
#include <cpptools/cpptoolsreuse.h>
#include <FullySpecifiedType.h>
#include <Literals.h>
......@@ -41,6 +42,7 @@
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
#include <TypeHierarchyBuilder.h>
#include <cplusplus/ModelManagerInterface.h>
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
......@@ -59,18 +61,6 @@ using namespace Internal;
using namespace CPlusPlus;
namespace {
void moveCursorToEndOfName(QTextCursor *tc) {
QTextDocument *doc = tc->document();
if (!doc)
return;
QChar ch = doc->characterAt(tc->position());
while (ch.isLetterOrNumber() || ch == QLatin1Char('_')) {
tc->movePosition(QTextCursor::NextCharacter);
ch = doc->characterAt(tc->position());
}
}
QStringList stripName(const QString &name) {
QStringList all;
all << name;
......@@ -88,7 +78,8 @@ CppElementEvaluator::CppElementEvaluator(CPPEditorWidget *editor) :
m_editor(editor),
m_modelManager(CppModelManagerInterface::instance()),
m_tc(editor->textCursor()),
m_lookupBaseClasses(false)
m_lookupBaseClasses(false),
m_lookupDerivedClasses(false)
{}
void CppElementEvaluator::setTextCursor(const QTextCursor &tc)
......@@ -97,6 +88,9 @@ void CppElementEvaluator::setTextCursor(const QTextCursor &tc)
void CppElementEvaluator::setLookupBaseClasses(const bool lookup)
{ m_lookupBaseClasses = lookup; }
void CppElementEvaluator::setLookupDerivedClasses(const bool lookup)
{ m_lookupDerivedClasses = lookup; }
// @todo: Consider refactoring code from CPPEditor::findLinkAt into here.
void CppElementEvaluator::execute()
{
......@@ -118,7 +112,7 @@ void CppElementEvaluator::execute()
checkDiagnosticMessage(doc, line);
if (!matchIncludeFile(doc, line) && !matchMacroInUse(doc, pos)) {
moveCursorToEndOfName(&m_tc);
CppTools::moveCursorToEndOfIdentifier(&m_tc);
// Fetch the expression's code
ExpressionUnderCursor expressionUnderCursor;
......@@ -185,13 +179,19 @@ void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
const FullySpecifiedType &type = declaration->type();
if (declaration->isNamespace()) {
m_element = QSharedPointer<CppElement>(new CppNamespace(declaration));
} else if (declaration->isClass() || declaration->isForwardClassDeclaration()) {
} else if (declaration->isClass()
|| declaration->isForwardClassDeclaration()
|| (declaration->isTemplate() && declaration->asTemplate()->declaration()
&& (declaration->asTemplate()->declaration()->isClass()
|| declaration->asTemplate()->declaration()->isForwardClassDeclaration()))) {
if (declaration->isForwardClassDeclaration())
if (Symbol *classDeclaration = snapshot.findMatchingClassDeclaration(declaration))
declaration = classDeclaration;
CppClass *cppClass = new CppClass(declaration);
if (m_lookupBaseClasses)
cppClass->lookupBases(declaration, context);
if (m_lookupDerivedClasses)
cppClass->lookupDerived(declaration, snapshot);
m_element = QSharedPointer<CppElement>(cppClass);
} else if (Enum *enumDecl = declaration->asEnum()) {
m_element = QSharedPointer<CppElement>(new CppEnum(enumDecl));
......@@ -199,13 +199,13 @@ void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
m_element = QSharedPointer<CppElement>(new CppEnumerator(enumerator));
} else if (declaration->isTypedef()) {
m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
} else if (declaration->isFunction() || (type.isValid() && type->isFunctionType())) {
} else if (declaration->isFunction()
|| (type.isValid() && type->isFunctionType())
|| declaration->isTemplate()) {
m_element = QSharedPointer<CppElement>(new CppFunction(declaration));
} else if (declaration->isDeclaration() && type.isValid()) {
m_element = QSharedPointer<CppElement>(
new CppVariable(declaration, context, lookupItem.scope()));
} else if (declaration->isTemplate() && declaration->asTemplate()->declaration()) {
m_element = QSharedPointer<CppElement>(new CppTemplate(declaration));
} else {
m_element = QSharedPointer<CppElement>(new CppDeclarableElement(declaration));
}
......@@ -327,6 +327,9 @@ CppMacro::~CppMacro()
{}
// CppDeclarableElement
CppDeclarableElement::CppDeclarableElement()
{}
CppDeclarableElement::CppDeclarableElement(Symbol *declaration) : CppElement()
{
m_icon = Icons().iconForSymbol(declaration);
......@@ -388,6 +391,9 @@ CppNamespace::~CppNamespace()
{}
// CppClass
CppClass::CppClass()
{}
CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
......@@ -428,9 +434,32 @@ void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &
}
}
void CppClass::lookupDerived(CPlusPlus::Symbol *declaration, const CPlusPlus::Snapshot &snapshot)
{
typedef QPair<CppClass *, TypeHierarchy> Data;
TypeHierarchyBuilder builder(declaration, snapshot);
const TypeHierarchy &completeHierarchy = builder.buildDerivedTypeHierarchy();
QQueue<Data> q;
q.enqueue(qMakePair(this, completeHierarchy));
while (!q.isEmpty()) {
const Data &current = q.dequeue();
CppClass *clazz = current.first;
const TypeHierarchy &classHierarchy = current.second;
foreach (const TypeHierarchy &derivedHierarchy, classHierarchy.hierarchy()) {
clazz->m_derived.append(CppClass(derivedHierarchy.symbol()));
q.enqueue(qMakePair(&clazz->m_derived.last(), derivedHierarchy));
}
}
}
const QList<CppClass> &CppClass::bases() const
{ return m_bases; }
const QList<CppClass> &CppClass::derived() const
{ return m_derived; }
// CppFunction
CppFunction::CppFunction(Symbol *declaration) : CppDeclarableElement(declaration)
{
......@@ -515,34 +544,6 @@ CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scop
CppVariable::~CppVariable()
{}
// CppTemplate
CppTemplate::CppTemplate(CPlusPlus::Symbol *declaration) : CppDeclarableElement(declaration)
{
Template *templateSymbol = declaration->asTemplate();
if (templateSymbol->declaration()->isClass() ||
templateSymbol->declaration()->isForwardClassDeclaration()) {
m_isClassTemplate = true;
setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
setTooltip(qualifiedName());
} else {
m_isClassTemplate = false;
setHelpCategory(TextEditor::HelpItem::Function);
}
}
CppTemplate::~CppTemplate()
{}
bool CppTemplate::isClassTemplate() const
{
return m_isClassTemplate;
}
bool CppTemplate::isFunctionTemplate() const
{
return !m_isClassTemplate;
}
CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
: CppDeclarableElement(declaration)
{
......
......@@ -68,6 +68,7 @@ public:
void setTextCursor(const QTextCursor &tc);
void setLookupBaseClasses(const bool lookup);
void setLookupDerivedClasses(const bool lookup);
void execute();
bool identifiedCppElement() const;
......@@ -88,6 +89,7 @@ private:
CPlusPlus::CppModelManagerInterface *m_modelManager;
QTextCursor m_tc;
bool m_lookupBaseClasses;
bool m_lookupDerivedClasses;
QSharedPointer<CppElement> m_element;
QString m_diagnosis;
};
......@@ -157,6 +159,7 @@ public:
class CppDeclarableElement : public CppElement
{
public:
CppDeclarableElement();
explicit CppDeclarableElement(CPlusPlus::Symbol *declaration);
virtual ~CppDeclarableElement();
......@@ -188,15 +191,19 @@ public:
class CppClass : public CppDeclarableElement
{
public:
CppClass();
explicit CppClass(CPlusPlus::Symbol *declaration);
virtual ~CppClass();
void lookupBases(CPlusPlus::Symbol *declaration, const CPlusPlus::LookupContext &context);
void lookupDerived(CPlusPlus::Symbol *declaration, const CPlusPlus::Snapshot &snapshot);
const QList<CppClass> &bases() const;
const QList<CppClass> &derived() const;
private:
QList<CppClass> m_bases;
QList<CppClass> m_derived;
};
class CppFunction : public CppDeclarableElement
......@@ -229,19 +236,6 @@ public:
virtual ~CppVariable();
};
class CppTemplate : public CppDeclarableElement
{
public:
explicit CppTemplate(CPlusPlus::Symbol *declaration);
virtual ~CppTemplate();
bool isClassTemplate() const;
bool isFunctionTemplate() const;
private:
bool m_isClassTemplate;
};
class CppEnumerator : public CppDeclarableElement
{
public:
......
......@@ -44,6 +44,7 @@
#include <QtCore/QLatin1Char>
#include <QtCore/QLatin1String>
#include <QtCore/QModelIndex>
#include <QtCore/QVector>
#include <QtGui/QVBoxLayout>
#include <QtGui/QStandardItemModel>
#include <QtGui/QLabel>
......@@ -52,6 +53,28 @@ using namespace CppEditor;
using namespace Internal;
using namespace Utils;
namespace {
enum ItemRole {
AnnotationRole = Qt::UserRole + 1,
LinkRole
};
QStandardItem *itemForClass(const CppClass &cppClass)
{
QStandardItem *item = new QStandardItem;
item->setData(cppClass.name(), Qt::DisplayRole);
if (cppClass.name() != cppClass.qualifiedName())
item->setData(cppClass.qualifiedName(), AnnotationRole);
item->setData(cppClass.icon(), Qt::DecorationRole);
QVariant link;
link.setValue(CPPEditorWidget::Link(cppClass.link()));
item->setData(link, LinkRole);
return item;
}
} // Anonymous
// CppTypeHierarchyWidget
CppTypeHierarchyWidget::CppTypeHierarchyWidget(Core::IEditor *editor) :
QWidget(0),
......@@ -67,16 +90,18 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget(Core::IEditor *editor) :
if (CPPEditor *cppEditor = qobject_cast<CPPEditor *>(editor)) {
m_cppEditor = static_cast<CPPEditorWidget *>(cppEditor->widget());
m_model = new QStandardItemModel;
m_treeView = new Utils::NavigationTreeView;
m_delegate = new AnnotatedItemDelegate;
m_model = new QStandardItemModel(this);
m_treeView = new NavigationTreeView(this);
m_delegate = new AnnotatedItemDelegate(this);
m_delegate->setDelimiter(QLatin1String(" "));
m_delegate->setAnnotationRole(AnnotationRole);
m_treeView->setModel(m_model);
m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_treeView->setItemDelegate(m_delegate);
m_treeView->setRootIsDecorated(false);
layout->addWidget(m_treeView);
connect(m_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(onItemClicked(QModelIndex)));
connect(m_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(onItemClicked(QModelIndex)));
connect(CppPlugin::instance(), SIGNAL(typeHierarchyRequested()), this, SLOT(perform()));
} else {
......@@ -90,10 +115,7 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget(Core::IEditor *editor) :
}
CppTypeHierarchyWidget::~CppTypeHierarchyWidget()
{
delete m_model;
delete m_delegate;
}
{}
bool CppTypeHierarchyWidget::handleEditorChange(Core::IEditor *editor)
{
......@@ -117,32 +139,52 @@ void CppTypeHierarchyWidget::perform()
CppElementEvaluator evaluator(m_cppEditor);
evaluator.setLookupBaseClasses(true);
evaluator.setLookupDerivedClasses(true);
evaluator.execute();
if (evaluator.identifiedCppElement()) {
const QSharedPointer<CppElement> &cppElement = evaluator.cppElement();
CppElement *element = cppElement.data();
if (CppClass *cppClass = dynamic_cast<CppClass *>(element))
buildModel(*cppClass, m_model->invisibleRootItem());
if (CppClass *cppClass = dynamic_cast<CppClass *>(element)) {
QStandardItem *bases = new QStandardItem(tr("Bases"));
m_model->invisibleRootItem()->appendRow(bases);
QVector<CppClass> v;
v.push_back(*cppClass);
buildBaseHierarchy(&v);
m_treeView->expand(m_model->indexFromItem(bases));
QStandardItem *derived = new QStandardItem(tr("Derived"));
m_model->invisibleRootItem()->appendRow(derived);
buildDerivedHierarchy(*cppClass, derived);
}
}
}
void CppTypeHierarchyWidget::buildModel(const CppClass &cppClass, QStandardItem *parent)
void CppTypeHierarchyWidget::buildBaseHierarchy(QVector<CppClass> *s)
{
QStandardItem *item = new QStandardItem;
parent->appendRow(item);
m_model->setData(m_model->indexFromItem(item), cppClass.name(), Qt::DisplayRole);
if (cppClass.name() != cppClass.qualifiedName())
m_model->setData(m_model->indexFromItem(item), cppClass.qualifiedName(), AnnotationRole);
m_model->setData(m_model->indexFromItem(item), cppClass.icon(), Qt::DecorationRole);
QVariant link;
link.setValue(CPPEditorWidget::Link(cppClass.link()));
m_model->setData(m_model->indexFromItem(item), link, LinkRole);
foreach (const CppClass &cppBase, cppClass.bases())
buildModel(cppBase, item);
const CppClass &current = s->back();
const QList<CppClass> &bases = current.bases();
if (!bases.isEmpty()) {