cppelementevaluator.cpp 15.9 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
hjk's avatar
hjk committed
3 4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22
** Alternatively, 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.
23
**
hjk's avatar
hjk committed
24 25
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30 31

#include "cppelementevaluator.h"

32
#include <coreplugin/idocument.h>
33
#include <cpptools/cpptoolsreuse.h>
34 35

#include <FullySpecifiedType.h>
36
#include <Literals.h>
37 38 39 40 41
#include <Names.h>
#include <CoreTypes.h>
#include <Scope.h>
#include <Symbol.h>
#include <Symbols.h>
42 43
#include <cpptools/TypeHierarchyBuilder.h>
#include <cpptools/ModelManagerInterface.h>
44 45 46 47 48 49 50
#include <cplusplus/ExpressionUnderCursor.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/LookupItem.h>
#include <cplusplus/Icons.h>

51 52 53 54
#include <QDir>
#include <QFileInfo>
#include <QSet>
#include <QQueue>
55 56 57 58 59 60

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

namespace {
61 62 63 64 65 66 67 68 69 70 71
    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;
    }
72 73
}

74
CppElementEvaluator::CppElementEvaluator(CPPEditorWidget *editor) :
75
    m_editor(editor),
76
    m_modelManager(CppModelManagerInterface::instance()),
77
    m_tc(editor->textCursor()),
78 79
    m_lookupBaseClasses(false),
    m_lookupDerivedClasses(false)
80 81 82 83 84 85 86 87
{}

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

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

88 89 90
void CppElementEvaluator::setLookupDerivedClasses(const bool lookup)
{ m_lookupDerivedClasses = lookup; }

91
// @todo: Consider refactoring code from CPPEditor::findLinkAt into here.
92
void CppElementEvaluator::execute()
93
{
94 95
    clear();

96 97 98 99
    if (!m_modelManager)
        return;

    const Snapshot &snapshot = m_modelManager->snapshot();
100
    Document::Ptr doc = snapshot.document(m_editor->editorDocument()->fileName());
101 102 103 104 105 106 107 108
    if (!doc)
        return;

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

109
    checkDiagnosticMessage(pos);
110

111
    if (!matchIncludeFile(doc, line) && !matchMacroInUse(doc, pos)) {
112
        CppTools::moveCursorToEndOfIdentifier(&m_tc);
113

114 115 116 117
        // Fetch the expression's code
        ExpressionUnderCursor expressionUnderCursor;
        const QString &expression = expressionUnderCursor(m_tc);
        Scope *scope = doc->scopeAt(line, column);
118

119 120
        TypeOfExpression typeOfExpression;
        typeOfExpression.init(doc, snapshot);
121
        const QList<LookupItem> &lookupItems = typeOfExpression(expression.toUtf8(), scope);
122 123 124 125 126
        if (lookupItems.isEmpty())
            return;

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

130
void CppElementEvaluator::checkDiagnosticMessage(int pos)
131
{
132 133 134 135
    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();
136
            break;
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        }
    }
}

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();
157
            if (pos < begin + use.macro().name().length()) {
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
                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));
178 179 180 181 182
        } else if (declaration->isClass()
                   || declaration->isForwardClassDeclaration()
                   || (declaration->isTemplate() && declaration->asTemplate()->declaration()
                       && (declaration->asTemplate()->declaration()->isClass()
                           || declaration->asTemplate()->declaration()->isForwardClassDeclaration()))) {
183
            if (declaration->isForwardClassDeclaration())
184
                if (Symbol *classDeclaration =
185
                        m_symbolFinder.findMatchingClassDeclaration(declaration, snapshot)) {
186
                    declaration = classDeclaration;
187
                }
188 189 190
            CppClass *cppClass = new CppClass(declaration);
            if (m_lookupBaseClasses)
                cppClass->lookupBases(declaration, context);
191 192
            if (m_lookupDerivedClasses)
                cppClass->lookupDerived(declaration, snapshot);
193
            m_element = QSharedPointer<CppElement>(cppClass);
194 195 196 197
        } 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));
198 199
        } else if (declaration->isTypedef()) {
            m_element = QSharedPointer<CppElement>(new CppTypedef(declaration));
200 201 202
        } else if (declaration->isFunction()
                   || (type.isValid() && type->isFunctionType())
                   || declaration->isTemplate()) {
203 204 205 206 207 208 209 210 211 212
            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));
        }
    }
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
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();
}

239
// CppElement
240
CppElement::CppElement() : helpCategory(TextEditor::HelpItem::Unknown)
241 242 243 244 245 246
{}

CppElement::~CppElement()
{}

// Unknown
247
Unknown::Unknown(const QString &type) : type(type)
248
{
249
    tooltip = type;
250 251 252 253 254 255
}


// CppInclude

CppInclude::CppInclude(const Document::Include &includeFile) :
256 257
    path(QDir::toNativeSeparators(includeFile.fileName())),
    fileName(QFileInfo(includeFile.fileName()).fileName())
258
{
259 260 261 262 263
    helpCategory = TextEditor::HelpItem::Brief;
    helpIdCandidates = QStringList(fileName);
    helpMark = fileName;
    link = CPPEditorWidget::Link(path);
    tooltip = path;
264 265 266
}

// CppMacro
267
CppMacro::CppMacro(const Macro &macro)
268
{
269
    helpCategory = TextEditor::HelpItem::Macro;
270
    const QString macroName = QLatin1String(macro.name());
271 272 273 274
    helpIdCandidates = QStringList(macroName);
    helpMark = macroName;
    link = CPPEditorWidget::Link(macro.fileName(), macro.line());
    tooltip = macro.toStringWithLineBreaks();
275 276 277
}

// CppDeclarableElement
278

279 280
CppDeclarableElement::CppDeclarableElement(Symbol *declaration) : CppElement()
{
281
    icon = Icons().iconForSymbol(declaration);
282 283

    Overview overview;
284 285
    overview.showArgumentNames = true;
    overview.showReturnTypes = true;
286
    name = overview.prettyName(declaration->name());
287 288 289
    if (declaration->enclosingScope()->isClass() ||
        declaration->enclosingScope()->isNamespace() ||
        declaration->enclosingScope()->isEnum()) {
290 291
        qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
        helpIdCandidates = stripName(qualifiedName);
292
    } else {
293 294
        qualifiedName = name;
        helpIdCandidates.append(name);
295 296
    }

297 298 299
    tooltip = overview.prettyType(declaration->type(), qualifiedName);
    link = CPPEditorWidget::linkToSymbol(declaration);
    helpMark = name;
300 301 302 303 304
}

// CppNamespace
CppNamespace::CppNamespace(Symbol *declaration) : CppDeclarableElement(declaration)
{
305 306
    helpCategory = TextEditor::HelpItem::ClassOrNamespace;
    tooltip = qualifiedName;
307 308 309 310 311
}

// CppClass
CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
312 313
    helpCategory = TextEditor::HelpItem::ClassOrNamespace;
    tooltip = qualifiedName;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
}

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;
338 339
                        cppClass->bases.append(baseCppClass);
                        q.enqueue(qMakePair(clazz, &cppClass->bases.last()));
340 341 342 343 344 345 346
                    }
                }
            }
        }
    }
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360
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()) {
361 362
            clazz->derived.append(CppClass(derivedHierarchy.symbol()));
            q.enqueue(qMakePair(&clazz->derived.last(), derivedHierarchy));
363 364 365 366
        }
    }
}

367
// CppFunction
368 369
CppFunction::CppFunction(Symbol *declaration)
    : CppDeclarableElement(declaration)
370
{
371
    helpCategory = TextEditor::HelpItem::Function;
372 373 374 375 376 377

    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;
378
    overview.showDefaultArguments = false;
379
    helpMark = overview.prettyType(type, name);
380

381
    overview.showFunctionSignatures = false;
382
    helpIdCandidates.append(overview.prettyName(declaration->name()));
383 384 385
}

// CppEnum
386 387
CppEnum::CppEnum(Enum *declaration)
    : CppDeclarableElement(declaration)
388
{
389 390
    helpCategory = TextEditor::HelpItem::Enum;
    tooltip = qualifiedName;
391 392 393
}

// CppTypedef
394
CppTypedef::CppTypedef(Symbol *declaration) : CppDeclarableElement(declaration)
395
{
396 397
    helpCategory = TextEditor::HelpItem::Typedef;
    tooltip = Overview().prettyType(declaration->type(), qualifiedName);
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
}

// 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));
426
                if (!name.isEmpty()) {
427 428
                    tooltip = name;
                    helpCategory = TextEditor::HelpItem::ClassOrNamespace;
429 430
                    const QStringList &allNames = stripName(name);
                    if (!allNames.isEmpty()) {
431 432
                        helpMark = allNames.last();
                        helpIdCandidates = allNames;
433 434
                    }
                }
435 436 437 438 439
            }
        }
    }
}

440 441 442
CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
    : CppDeclarableElement(declaration)
{
443
    helpCategory = TextEditor::HelpItem::Enum;
444 445 446 447 448 449 450

    Overview overview;

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

454
    helpMark = overview.prettyName(enumSymbol->name());
455

456
    tooltip = enumeratorName;
457 458 459 460 461
    if (!enumName.isEmpty())
        tooltip.prepend(enumName + QLatin1Char(' '));
    if (!enumeratorValue.isEmpty())
        tooltip.append(QLatin1String(" = ") + enumeratorValue);
}