cppelementevaluator.cpp 18.2 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** 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.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
29
** Nokia at qt-info@nokia.com.
30 31 32 33 34 35
**
**************************************************************************/

#include "cppelementevaluator.h"

#include <coreplugin/ifile.h>
36
#include <cpptools/cpptoolsreuse.h>
37
#include <cpptools/symbolfinder.h>
38 39

#include <FullySpecifiedType.h>
40
#include <Literals.h>
41 42 43 44 45
#include <Names.h>
#include <CoreTypes.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
46
#include <TypeHierarchyBuilder.h>
47
#include <cplusplus/ModelManagerInterface.h>
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/LookupItem.h>
#include <cplusplus/Icons.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QSet>
#include <QtCore/QQueue>

using namespace CppEditor;
using namespace Internal;
using namespace CPlusPlus;

namespace {
65 66 67 68 69 70 71 72 73 74 75
    QStringList stripName(const QString &name) {
        QStringList all;
        all << name;
        int colonColon = 0;
        const int size = name.size();
        while ((colonColon = name.indexOf(QLatin1String("::"), colonColon)) != -1) {
            all << name.right(size - colonColon - 2);
            colonColon += 2;
        }
        return all;
    }
76 77
}

78
CppElementEvaluator::CppElementEvaluator(CPPEditorWidget *editor) :
79
    m_editor(editor),
80
    m_modelManager(CppModelManagerInterface::instance()),
81
    m_tc(editor->textCursor()),
82 83
    m_lookupBaseClasses(false),
    m_lookupDerivedClasses(false)
84 85 86 87 88 89 90 91
{}

void CppElementEvaluator::setTextCursor(const QTextCursor &tc)
{ m_tc = tc; }

void CppElementEvaluator::setLookupBaseClasses(const bool lookup)
{ m_lookupBaseClasses = lookup; }

92 93 94
void CppElementEvaluator::setLookupDerivedClasses(const bool lookup)
{ m_lookupDerivedClasses = lookup; }

95
// @todo: Consider refactoring code from CPPEditor::findLinkAt into here.
96
void CppElementEvaluator::execute()
97
{
98 99
    clear();

100 101 102 103 104 105 106 107 108 109 110 111 112
    if (!m_modelManager)
        return;

    const Snapshot &snapshot = m_modelManager->snapshot();
    Document::Ptr doc = snapshot.document(m_editor->file()->fileName());
    if (!doc)
        return;

    int line = 0;
    int column = 0;
    const int pos = m_tc.position();
    m_editor->convertPosition(pos, &line, &column);

113
    checkDiagnosticMessage(pos);
114

115
    if (!matchIncludeFile(doc, line) && !matchMacroInUse(doc, pos)) {
116
        CppTools::moveCursorToEndOfIdentifier(&m_tc);
117

118 119 120 121
        // Fetch the expression's code
        ExpressionUnderCursor expressionUnderCursor;
        const QString &expression = expressionUnderCursor(m_tc);
        Scope *scope = doc->scopeAt(line, column);
122

123 124
        TypeOfExpression typeOfExpression;
        typeOfExpression.init(doc, snapshot);
125
        const QList<LookupItem> &lookupItems = typeOfExpression(expression.toUtf8(), scope);
126 127 128 129 130
        if (lookupItems.isEmpty())
            return;

        const LookupItem &lookupItem = lookupItems.first(); // ### TODO: select best candidate.
        handleLookupItemMatch(snapshot, lookupItem, typeOfExpression.context());
131 132 133
    }
}

134
void CppElementEvaluator::checkDiagnosticMessage(int pos)
135
{
136 137 138 139
    foreach (const QTextEdit::ExtraSelection &sel,
             m_editor->extraSelections(TextEditor::BaseTextEditorWidget::CodeWarningsSelection)) {
        if (pos >= sel.cursor.selectionStart() && pos <= sel.cursor.selectionEnd()) {
            m_diagnosis = sel.format.toolTip();
140
            break;
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        }
    }
}

bool CppElementEvaluator::matchIncludeFile(const CPlusPlus::Document::Ptr &document, unsigned line)
{
    foreach (const Document::Include &includeFile, document->includes()) {
        if (includeFile.line() == line) {
            m_element = QSharedPointer<CppElement>(new CppInclude(includeFile));
            return true;
        }
    }
    return false;
}

bool CppElementEvaluator::matchMacroInUse(const CPlusPlus::Document::Ptr &document, unsigned pos)
{
    foreach (const Document::MacroUse &use, document->macroUses()) {
        if (use.contains(pos)) {
            const unsigned begin = use.begin();
161
            if (pos < begin + use.macro().name().length()) {
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
                m_element = QSharedPointer<CppElement>(new CppMacro(use.macro()));
                return true;
            }
        }
    }
    return false;
}

void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
                                                const LookupItem &lookupItem,
                                                const LookupContext &context)
{
    Symbol *declaration = lookupItem.declaration();
    if (!declaration) {
        const QString &type = Overview().prettyType(lookupItem.type(), QString());
        m_element = QSharedPointer<CppElement>(new Unknown(type));
    } else {
        const FullySpecifiedType &type = declaration->type();
        if (declaration->isNamespace()) {
            m_element = QSharedPointer<CppElement>(new CppNamespace(declaration));
182 183 184 185 186
        } else if (declaration->isClass()
                   || declaration->isForwardClassDeclaration()
                   || (declaration->isTemplate() && declaration->asTemplate()->declaration()
                       && (declaration->asTemplate()->declaration()->isClass()
                           || declaration->asTemplate()->declaration()->isForwardClassDeclaration()))) {
187
            if (declaration->isForwardClassDeclaration())
188 189 190
                if (Symbol *classDeclaration =
                        m_editor->symbolFinder()->findMatchingClassDeclaration(
                            declaration, snapshot)) {
191
                    declaration = classDeclaration;
192
                }
193 194 195
            CppClass *cppClass = new CppClass(declaration);
            if (m_lookupBaseClasses)
                cppClass->lookupBases(declaration, context);
196 197
            if (m_lookupDerivedClasses)
                cppClass->lookupDerived(declaration, snapshot);
198
            m_element = QSharedPointer<CppElement>(cppClass);
199 200 201 202
        } else if (Enum *enumDecl = declaration->asEnum()) {
            m_element = QSharedPointer<CppElement>(new CppEnum(enumDecl));
        } else if (EnumeratorDeclaration *enumerator = dynamic_cast<EnumeratorDeclaration *>(declaration)) {
            m_element = QSharedPointer<CppElement>(new CppEnumerator(enumerator));
203 204
        } else if (declaration->isTypedef()) {
            m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
205 206 207
        } else if (declaration->isFunction()
                   || (type.isValid() && type->isFunctionType())
                   || declaration->isTemplate()) {
208 209 210 211 212 213 214 215 216 217
            m_element = QSharedPointer<CppElement>(new CppFunction(declaration));
        } else if (declaration->isDeclaration() && type.isValid()) {
            m_element = QSharedPointer<CppElement>(
                new CppVariable(declaration, context, lookupItem.scope()));
        } else {
            m_element = QSharedPointer<CppElement>(new CppDeclarableElement(declaration));
        }
    }
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
bool CppElementEvaluator::identifiedCppElement() const
{
    return !m_element.isNull();
}

const QSharedPointer<CppElement> &CppElementEvaluator::cppElement() const
{
    return m_element;
}

bool CppElementEvaluator::hasDiagnosis() const
{
    return !m_diagnosis.isEmpty();
}

const QString &CppElementEvaluator::diagnosis() const
{
    return m_diagnosis;
}

void CppEditor::Internal::CppElementEvaluator::clear()
{
    m_element.clear();
    m_diagnosis.clear();
}

244
// CppElement
245
CppElement::CppElement() : m_helpCategory(TextEditor::HelpItem::Unknown)
246 247 248 249 250
{}

CppElement::~CppElement()
{}

251
void CppElement::setHelpCategory(const TextEditor::HelpItem::Category &cat)
252 253
{ m_helpCategory = cat; }

254
const TextEditor::HelpItem::Category &CppElement::helpCategory() const
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
{ return m_helpCategory; }

void CppElement::setHelpIdCandidates(const QStringList &candidates)
{ m_helpIdCandidates = candidates; }

void CppElement::addHelpIdCandidate(const QString &candidate)
{ m_helpIdCandidates.append(candidate); }

const QStringList &CppElement::helpIdCandidates() const
{ return m_helpIdCandidates; }

void CppElement::setHelpMark(const QString &mark)
{ m_helpMark = mark; }

const QString &CppElement::helpMark() const
{ return m_helpMark; }

272
void CppElement::setLink(const CPPEditorWidget::Link &link)
273 274
{ m_link = link; }

275
const CPPEditorWidget::Link &CppElement::link() const
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
{ return m_link; }

void CppElement::setTooltip(const QString &tooltip)
{ m_tooltip = tooltip; }

const QString &CppElement::tooltip() const
{ return m_tooltip; }


// Unknown
Unknown::Unknown(const QString &type) : CppElement(), m_type(type)
{
    setTooltip(m_type);
}

Unknown::~Unknown()
{}

const QString &Unknown::type() const
{ return m_type; }

// CppInclude
CppInclude::~CppInclude()
{}

CppInclude::CppInclude(const Document::Include &includeFile) :
    CppElement(),
    m_path(QDir::toNativeSeparators(includeFile.fileName())),
    m_fileName(QFileInfo(includeFile.fileName()).fileName())
{
306
    setHelpCategory(TextEditor::HelpItem::Brief);
307 308
    setHelpIdCandidates(QStringList(m_fileName));
    setHelpMark(m_fileName);
309
    setLink(CPPEditorWidget::Link(m_path));
310 311 312 313 314 315 316 317 318 319 320 321
    setTooltip(m_path);
}

const QString &CppInclude::path() const
{ return m_path; }

const QString &CppInclude::fileName() const
{ return m_fileName; }

// CppMacro
CppMacro::CppMacro(const Macro &macro) : CppElement()
{
322
    setHelpCategory(TextEditor::HelpItem::Macro);
323 324 325
    const QString macroName = QLatin1String(macro.name());
    setHelpIdCandidates(QStringList(macroName));
    setHelpMark(macroName);
326
    setLink(CPPEditorWidget::Link(macro.fileName(), macro.line()));
327
    setTooltip(macro.toStringWithLineBreaks());
328 329 330 331 332 333
}

CppMacro::~CppMacro()
{}

// CppDeclarableElement
334 335 336
CppDeclarableElement::CppDeclarableElement()
{}

337 338
CppDeclarableElement::CppDeclarableElement(Symbol *declaration) : CppElement()
{
339
    m_icon = Icons().iconForSymbol(declaration);
340 341 342 343 344

    Overview overview;
    overview.setShowArgumentNames(true);
    overview.setShowReturnTypes(true);
    m_name = overview.prettyName(declaration->name());
345 346 347
    if (declaration->enclosingScope()->isClass() ||
        declaration->enclosingScope()->isNamespace() ||
        declaration->enclosingScope()->isEnum()) {
348
        m_qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
349
        setHelpIdCandidates(stripName(m_qualifiedName));
350 351
    } else {
        m_qualifiedName = m_name;
352
        setHelpIdCandidates(QStringList(m_name));
353 354
    }

355
    setTooltip(overview.prettyType(declaration->type(), m_qualifiedName));
356
    setLink(CPPEditorWidget::linkToSymbol(declaration));
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    setHelpMark(m_name);
}

CppDeclarableElement::~CppDeclarableElement()
{}

void CppDeclarableElement::setName(const QString &name)
{ m_name = name; }

const QString &CppDeclarableElement::name() const
{ return m_name; }

void CppDeclarableElement::setQualifiedName(const QString &name)
{ m_qualifiedName = name; }

const QString &CppDeclarableElement::qualifiedName() const
{ return m_qualifiedName; }

void CppDeclarableElement::setType(const QString &type)
{ m_type = type; }

const QString &CppDeclarableElement::type() const
{ return m_type; }

void CppDeclarableElement::setIcon(const QIcon &icon)
{ m_icon = icon; }

const QIcon &CppDeclarableElement::icon() const
{ return m_icon; }

// CppNamespace
CppNamespace::CppNamespace(Symbol *declaration) : CppDeclarableElement(declaration)
{
390
    setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
391
    setTooltip(qualifiedName());
392 393 394 395 396 397
}

CppNamespace::~CppNamespace()
{}

// CppClass
398 399 400
CppClass::CppClass()
{}

401 402
CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
403
    setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
404
    setTooltip(qualifiedName());
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
}

CppClass::~CppClass()
{}

void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &context)
{
    typedef QPair<ClassOrNamespace *, CppClass *> Data;

    if (ClassOrNamespace *clazz = context.lookupType(declaration)) {
        QSet<ClassOrNamespace *> visited;

        QQueue<Data> q;
        q.enqueue(qMakePair(clazz, this));
        while (!q.isEmpty()) {
            Data current = q.dequeue();
            clazz = current.first;
            visited.insert(clazz);
            const QList<ClassOrNamespace *> &bases = clazz->usings();
            foreach (ClassOrNamespace *baseClass, bases) {
                const QList<Symbol *> &symbols = baseClass->symbols();
                foreach (Symbol *symbol, symbols) {
                    if (symbol->isClass() && (
                        clazz = context.lookupType(symbol)) &&
                        !visited.contains(clazz)) {
                        CppClass baseCppClass(symbol);
                        CppClass *cppClass = current.second;
                        cppClass->m_bases.append(baseCppClass);
                        q.enqueue(qMakePair(clazz, &cppClass->m_bases.last()));
                    }
                }
            }
        }
    }
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
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));
        }
    }
}

461 462 463
const QList<CppClass> &CppClass::bases() const
{ return m_bases; }

464 465 466
const QList<CppClass> &CppClass::derived() const
{ return m_derived; }

467 468 469
// CppFunction
CppFunction::CppFunction(Symbol *declaration) : CppDeclarableElement(declaration)
{
470
    setHelpCategory(TextEditor::HelpItem::Function);
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    const FullySpecifiedType &type = declaration->type();

    // Functions marks can be found either by the main overload or signature based
    // (with no argument names and no return). Help ids have no signature at all.
    Overview overview;
    overview.setShowDefaultArguments(false);
    setHelpMark(overview.prettyType(type, name()));

    overview.setShowFunctionSignatures(false);
    addHelpIdCandidate(overview.prettyName(declaration->name()));
}

CppFunction::~CppFunction()
{}

// CppEnum
488 489
CppEnum::CppEnum(Enum *declaration)
    : CppDeclarableElement(declaration)
490
{
491
    setHelpCategory(TextEditor::HelpItem::Enum);
492
    setTooltip(qualifiedName());
493 494 495 496 497 498
}

CppEnum::~CppEnum()
{}

// CppTypedef
499
CppTypedef::CppTypedef(Symbol *declaration) : CppDeclarableElement(declaration)
500
{
501
    setHelpCategory(TextEditor::HelpItem::Typedef);
502
    setTooltip(Overview().prettyType(declaration->type(), qualifiedName()));
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
}

CppTypedef::~CppTypedef()
{}

// CppVariable
CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scope *scope) :
    CppDeclarableElement(declaration)
{
    const FullySpecifiedType &type = declaration->type();

    const Name *typeName = 0;
    if (type->isNamedType()) {
        typeName = type->asNamedType()->name();
    } else if (type->isPointerType() || type->isReferenceType()) {
        FullySpecifiedType associatedType;
        if (type->isPointerType())
            associatedType = type->asPointerType()->elementType();
        else
            associatedType = type->asReferenceType()->elementType();
        if (associatedType->isNamedType())
            typeName = associatedType->asNamedType()->name();
    }

    if (typeName) {
        if (ClassOrNamespace *clazz = context.lookupType(typeName, scope)) {
            if (!clazz->symbols().isEmpty()) {
                Overview overview;
                Symbol *symbol = clazz->symbols().at(0);
                const QString &name =
                    overview.prettyName(LookupContext::fullyQualifiedName(symbol));
534 535 536 537 538 539 540 541 542
                if (!name.isEmpty()) {
                    setTooltip(name);
                    setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
                    const QStringList &allNames = stripName(name);
                    if (!allNames.isEmpty()) {
                        setHelpMark(allNames.last());
                        setHelpIdCandidates(allNames);
                    }
                }
543 544 545 546 547 548 549
            }
        }
    }
}

CppVariable::~CppVariable()
{}
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
    : CppDeclarableElement(declaration)
{
    setHelpCategory(TextEditor::HelpItem::Enum);

    Overview overview;

    Symbol *enumSymbol = declaration->enclosingScope()->asEnum();
    const QString enumName = overview.prettyName(LookupContext::fullyQualifiedName(enumSymbol));
    const QString enumeratorName = overview.prettyName(declaration->name());
    QString enumeratorValue;
    if (const StringLiteral *value = declaration->constantValue()) {
        enumeratorValue = QString::fromUtf8(value->chars(), value->size());
    }

    setHelpMark(overview.prettyName(enumSymbol->name()));

    QString tooltip = enumeratorName;
    if (!enumName.isEmpty())
        tooltip.prepend(enumName + QLatin1Char(' '));
    if (!enumeratorValue.isEmpty())
        tooltip.append(QLatin1String(" = ") + enumeratorValue);
    setTooltip(tooltip);
}

CppEnumerator::~CppEnumerator()
{}